#include "dealmsgpacket.h"

#include <iostream>
#include <QFile>
#include <QImage>
#include <QDebug>
#include <QUrl>
#include <QThread>
#include <QCryptographicHash>  //md5加密的库
#include <QBuffer>
#include <QAbstractSocket>
#include <QJsonObject>
#include <QJsonDocument>
#include <QUdpSocket>
#include <QPainter>
#include <QPen>
#include <QtMath>
#include <QImageReader>
#include <stdlib.h>
#include <functional>
#include <cstring> // 引入strlen函数所需的头文件

#include "./beans/systemconfig.h"
#include <iostream>
#include "xpack/json.h" // Json包含这个头文件，xml则包含xpack/xml.h
#include "xpack/xpack_common.h"

using namespace std;
using namespace xpack;

/**
 * @brief MySocket::MySocket
 * @param parent
 * @author xxz
 */
MySocket::MySocket(QObject* parent):QObject(parent)
{
    socket = new QWebSocket;
    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
    connect(socket,&QWebSocket::connected,this,&MySocket::doConnected);
    connect(socket,&QWebSocket::disconnected,this,&MySocket::doDisConnected);
    connect(socket,&QWebSocket::textMessageReceived,this,&MySocket::doTextOccured);
    connect(socket,&QWebSocket::binaryMessageReceived,this,&MySocket::doBinaryOccured);
}

MySocket::~MySocket(){
    socket->close();
    delete socket;
    socket = NULL;
}

void MySocket::doConnected(){
    emit onConnected();
    qDebug() << "connected to server !";
}

void MySocket::doDisConnected(){
    emit onDisConnected();

    if(QAbstractSocket::UnconnectedState == socket->state()){
        qDebug() << "disConnected from server ! connecting...";
    }
}

void MySocket::doTextOccured(const QString& msg){
    emit onTextOccured(msg);
}

void MySocket::doBinaryOccured(const QByteArray& msg){
    emit onBinaryOccured(msg);
}

QWebSocket* MySocket::getSocket(){
    return socket;
}

/***********************************************************************/

DoDataThread::DoDataThread(QObject *parent):QObject(parent)
{
    auto configIntance = SystemConfig::getInstance();

    //获取websocket客户端的ip和port
    QString ip = configIntance->value("server/ip","127.0.0.1").toString();
    QString port = configIntance->value("server/port","10000").toString();

    //打开websocket
    QString requestUrl = QString("ws://%1:%2").arg(ip).arg(port);
    m_ServerUrl = QUrl(requestUrl);

    m_MySocket = new MySocket;
    m_Timer = new QTimer();

    m_SocketThread =  new QThread(this);
    m_SocketThread->setObjectName("webSocketThread");
    m_MySocket->moveToThread(m_SocketThread);
    m_SocketThread->start();

    m_Thread = new std::thread(&DoDataThread::run,this);
    m_Thread->detach();

    __initSlots();
}

void DoDataThread::doReConnect(){
    m_MySocket->getSocket()->open(m_ServerUrl);
}

DoDataThread::~DoDataThread(){

    m_MsgQueue.empty();

    delete m_MySocket;
    m_MySocket = nullptr;

    delete m_SocketThread;
    m_SocketThread = nullptr;

    m_Timer->stop();
    delete m_Timer;
    m_Timer = nullptr;

    if(!m_Thread->joinable()){
        delete m_Thread;
        m_Thread = NULL;
    }
}

void DoDataThread::sendMsg(const QString &msg,const bool& isGetPicInfo){
    std::unique_lock<std::mutex> lock(m_Mutex);
    //m_MsgQueue.push(msg);
    if(isGetPicInfo){
        m_MsgQueue.push(msg);
    }else
        m_MsgQueue.push(msg);

    if(is_Waiting){
        m_Condition.notify_all();
        is_Waiting = false;
    }

    //qDebug() << "push:" << msg;
}

void DoDataThread::doMessage(QString msg){
    //发送消息
    m_MySocket->getSocket()->sendTextMessage(msg);
    m_MySocket->getSocket()->flush();
}

void DoDataThread::__initSlots(){
    connect(this,&DoDataThread::onMessage,this,&DoDataThread::doMessage);

    connect(m_MySocket,&MySocket::onTextOccured,this,&DoDataThread::onTextMessageReceived);
    connect(m_MySocket,&MySocket::onBinaryOccured,this,&DoDataThread::doBinaryMessage);
    connect(m_MySocket,&MySocket::onConnected,this,&DoDataThread::stopTimer);
    connect(this,&DoDataThread::stopTimer,[&](){
        emit onNetConnect(true);
        m_Timer->stop();
    });
    connect(m_MySocket,&MySocket::onDisConnected,this,&DoDataThread::startTimer);
    connect(this,&DoDataThread::startTimer,[&](){
        emit onNetConnect(false);
        m_Timer->start();
    });

    connect(m_Timer,&QTimer::timeout,this,&DoDataThread::doReConnect);
    m_Timer->start(1500);
}

void DoDataThread::run(){
    while(1){
        std::unique_lock<std::mutex> lock(m_Mutex);
        if(m_MsgQueue.size() <= 0){
            is_Waiting = true;
        }
        m_Condition.wait(lock,[&]{ return m_MsgQueue.size() > 0;});

        QString msg = m_MsgQueue.front();
        emit onMessage(msg);
        //队列消息弹出
        m_MsgQueue.pop();

        std::this_thread::sleep_for (std::chrono::milliseconds(20));

        if(SystemConfig::getInstance()->value("info/flag",false).toBool()){
            qDebug() << "client send : \n" << msg;
        }
    }
}

void DoDataThread::onTextMessageReceived(QString msg){
    emit onCallBack(msg);
}

void DoDataThread::doBinaryMessage(const QByteArray& data){
    emit onCallBinaryBack(data);
}

/*****************************************************************/

int MsgControl::m_PrintJingDuList[6] = {180, 240, 360, 480, 720, 1080};
MsgControl::MsgControl(QObject *parent) : QObject(parent),
    m_DoDataThread(std::make_shared<DoDataThread>())
{
    connect(m_DoDataThread.get(),&DoDataThread::onCallBack,this,&MsgControl::doCallBack);
    connect(m_DoDataThread.get(),&DoDataThread::onCallBinaryBack,this,&MsgControl::doCallBinaryBack);
    connect(m_DoDataThread.get(),&DoDataThread::onNetConnect,this,&MsgControl::doNetConnect);

    //单位制 mm | inch | thickness | paperwidth
    m_SizeUnit = SystemConfig::getInstance()->value("setting/sizeunit","mm").toString();
    m_PaperWidth = SystemConfig::getInstance()->value("setting/paperwidth","330").toString();
    m_Language = SystemConfig::getInstance()->value("setting/language","en").toString();
    //m_ThickNess = SystemConfig::getInstance()->value("setting/thickness","smooth").toString();
    QVariantList inkSettingList ;
    inkSettingList << 0 << 0 << 0 << 0 << 0 << 0;
    m_InkList = SystemConfig::getInstance()->value("setting/inkSetting",inkSettingList).toList();
    m_RIPThreads = SystemConfig::getInstance()->value("setting/ripThreads",1).toInt();

    //版本日期
    std::function<QString(void)> version = [](void){
        QString compileDate = __DATE__;//取编译时间
        QStringList list = compileDate.split(" ");
        foreach (const QString& str, list) {
            if(str.isEmpty()) list.removeAt(1);
        }

        if(list.at(1).toInt() <=9)
            list.replace(1,QString("0%1").arg(list.at(1)));

        QString date = list.join("-");
        QString finalMonth = date.split("-").at(0);
        QStringList monthListStr = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        int index = monthListStr.indexOf(finalMonth);
        date.replace(finalMonth,QString("%1%2").arg(8 >= index ? "0":"", QString::number(index+1)));
        return date;
    };

    m_SoftWareVersion = "V-" + version();
}

MsgControl::~MsgControl(){
    m_DoDataThread = nullptr;
}

void MsgControl::publishMsg(const QString& msg){
    m_DoDataThread->sendMsg(msg);
}

std::string MsgControl::cppJson_To_String(const Json::Value & root){
    //关键在于对builder的属性设置
    Json::StreamWriterBuilder builder;
    static Json::Value def = []() {
        Json::Value def;
        Json::StreamWriterBuilder::setDefaults(&def);
        def["emitUTF8"] = true;
        def["indentation"] = "";
        return def;
    }();
    builder.settings_ = def;
    const std::unique_ptr<Json::StreamWriter> jsonWriter(builder.newStreamWriter());
    std::ostringstream jsonStream;

    jsonWriter->write(root, &jsonStream);

    return jsonStream.str();
}

bool MsgControl::generateWifiCode(const QString value,const QString path){
    QRcode *qr = QRcode_encodeString(value.toStdString().data(), 0, QR_ECLEVEL_H, QR_MODE_8, 1);
    QImage image(200, 200, QImage::Format_ARGB32);

    int scale = 10; //方块绘制大小
    if (qr && qr->width > 0)
    {
        int img_width = qr->width * scale;
        image = image.scaled(img_width, img_width);
        QPainter painter(&image);
        painter.fillRect(0, 0, img_width, img_width, Qt::white);//背景填充白色
        QPen pen;
        pen.setColor("#1989FA");
        painter.setPen(pen);

        for (int y = 0; y < qr->width; y++) //行
        {
            for (int x = 0; x < qr->width; x++) //列
            {
                if (qr->data[y * qr->width + x] & 1) //1表示黑块
                {
                    QRect r(x * scale, y * scale, scale, scale);
                    QColor color("#1989FA"); // 设置颜色为红色
                    painter.setBrush(color); // 设置画刷颜色
                    painter.drawRects(&r,1);
                }
            }
        }
        painter.end();
        QRcode_free(qr);

        // 使用 QImage 将二维码保存为图片, 字符串扩展名决定了图像编码格式.
        image.save(path);
        return true;
    }else{
        QRcode_free(qr);
        return false;
    }
}

bool MsgControl::isProgressiveJPEG(const QString &filePath) {
    QImageReader reader(filePath);
    QString format = reader.format();
    return (format.toLower() == "jpeg" || format.toLower() == "jpg") && reader.imageCount() > 1;
}

void MsgControl::setStartBtnStatus(int status){
    m_StartBtnStatus = status;
    if(2 == status || 3 == status){
        setPageChange(0);
        emit swipePagesSilder(false);
    }else{
        emit swipePagesSilder(true);
    }
    emit startBtnStatusChanged();
}

int MsgControl::getStartBtnStatus(){
    return m_StartBtnStatus;
}

void MsgControl::setErrorMsg(const QVariantMap& error){
    this->m_ErrorMsg = error;
    emit errorMsgChanged();
}

bool MsgControl::getNetConnected(){
    return m_NetConnected;
}

QVariantMap MsgControl::getErrorMsg(){
    return m_ErrorMsg;
}

void MsgControl::setFileList(const QVariantList& fileList){
    m_FileList = fileList;
    emit fileListChanged();
}

QVariantList MsgControl::getFileList(){
    return m_FileList;
}

QVariantMap MsgControl::getPicPropertyMap(){
    return m_PicpPropertyMap;
}

void MsgControl::setPicPropertyMap(const QVariantMap & picMap){
    m_PicpPropertyMap = picMap;
    emit picPropertyMapChanged();
}

void MsgControl::setPrintProcess(const double & process){
    this->m_PrintProcess = process;
    emit printProcessChanged();
}

double MsgControl::getPrintProcess(){
    return m_PrintProcess;
}

void MsgControl::setPrintTip(const QString &tip){
    m_PrintTip = tip;
    emit printTipChanged();
}

QString MsgControl::getPrintTip(){
    return m_PrintTip;
}

void MsgControl::setPrintBarShow(const bool & flag){
    m_PrintBarShow = flag;
    emit printBarShowChanged();
}

bool MsgControl::getPrintBarShow(){
    return m_PrintBarShow;
}

void MsgControl::setSelectPicture(const bool & flag){
    m_IsSelectPicture = flag;
    if(!flag){
        m_SeletcedFileMap.clear();
        m_SelectedFilesList.clear();
        m_FileInfoMap.clear();
    }
    emit selectPictureChanged();
}

bool MsgControl::getSelectPicture(){
    return m_IsSelectPicture;
}

void MsgControl::setStateTypeMap(const QVariantMap & map){
    m_SateTypeMap = map;
    emit stateTypeMapChanged();
}

QVariantMap MsgControl::getStateTypeMap(){
    return m_SateTypeMap;
}

bool MsgControl::getShowTapPic(){
    return m_ShowPicture;
}

void MsgControl::setShowTapPic(const bool &flag){
    m_ShowPicture = flag;
    emit showTapPicChanged();
}

QVariantList MsgControl::getPaiBanFileList(){
    return m_seletePaiBanFileList;
}

void MsgControl::setPaiBanFileList(const QVariantList &list){
    m_seletePaiBanFileList = list;

    if(isAutoBingPack){
        if(0 >= m_seletePaiBanFileList.size()){
            emit refreshPackView({});
            return;
        }
        //通知进行一次自动排版计算
        emit onGetBigPic(m_seletePaiBanFileList);
        //进入等待排版完成...
        emit showWaitDia(true);
    }else{
        double p_h = 0;//排版的总高度
        const QVariantList& retList = buildRealPackListView(m_seletePaiBanFileList,p_h);
        setPaperHeight(QString::number(p_h));

        emit onDealPackList(retList,p_h);
        emit refreshPackView(retList);
    }
    emit paiBanFileListChanged();
}

void MsgControl::setCopy(const QVariantList& list){
    if(list[0].toInt() < 0 || list[1].toInt() < 0) return;

    m_CurrentPicIndex  = -1; //还原

    QVariantMap* tempMap = (QVariantMap*)m_seletePaiBanFileList.at(list[0].toInt()).data();
    if(list[1].toInt() == (*tempMap)["copy"]){
        return;
    }else{
        (*tempMap)["copy"] = list[1].toInt();
    }

    //统计删除之后，排版显示区域移动到的索引位置
    int rows = list[0].toInt() + 1;
    for(int i = 0 ; i < rows;i++)
    {
        m_CurrentPicIndex += m_seletePaiBanFileList.at(i).toMap()["copy"].toInt();
    }

    setPaiBanFileList(m_seletePaiBanFileList);
}

void MsgControl::setSpacing(const double& gap){
    if(gap < 0) return;

    if("mm" == m_SizeUnit){
        if(gap == m_PictureGap){
            return;
        }else{
            m_PictureGap = gap;
        }
    }else{
        if(gap*254 * 1.0 /10 == m_PictureGap){
            return;
        }else{
            m_PictureGap = gap*254 * 1.0 /10;
        }
    }

    emit spacingChanged();
    emit onPicGap(m_PictureGap);
    setPaiBanFileList(m_seletePaiBanFileList);
}

double MsgControl::getSpacing(){
    return m_PictureGap;
}

void MsgControl::setWidthHeight(const QVariantList& list){
    if(list[0].toInt() < 0 || list[1].toFloat() < 0 || list[2].toFloat() < 0) return;
    QVariantMap* tempMap = (QVariantMap*)m_seletePaiBanFileList.at(list[0].toInt()).data();
    const bool& extend = (*tempMap)["extend"].toBool();
    if(extend){
        setPaiBanFileList(m_seletePaiBanFileList);
        return;
    }

    float initScale = (*tempMap)["initScale"].toFloat();
    if("mm" == m_SizeUnit){
        if(list[1].toDouble() != (*tempMap)["width"].toDouble()){
            (*tempMap)["width"] = list[1].toString();
            (*tempMap)["height"] = QString::number(list[1].toFloat() / initScale,'f',3);
        }else if(list[2].toDouble() != (*tempMap)["height"].toDouble()){
            (*tempMap)["height"] = list[2].toString();
            (*tempMap)["width"] = QString::number(list[2].toFloat() * initScale,'f',3);
        }
    }else{
        QString tempW = QString::number((*tempMap)["width"].toDouble()*10.0 / 254,'f',3);
        QString tempH = QString::number((*tempMap)["height"].toDouble()*10.0 / 254,'f',3);
        if(list[1].toDouble() != tempW.toDouble()){
            (*tempMap)["width"] = QString::number(list[1].toFloat() * 254 /10,'f',3);
            (*tempMap)["height"] = QString::number(list[1].toFloat()* 254 /10 / initScale,'f',3);
        }else if(list[2].toDouble() != tempH.toDouble()){
            (*tempMap)["height"] = QString::number(list[2].toFloat()* 254 /10,'f',3) ;
            (*tempMap)["width"] = QString::number(list[2].toFloat() * 254 /10 * initScale,'f',3);
        }
    }

    (*tempMap)["originWidth"] = (*tempMap)["width"];
    (*tempMap)["originHeight"] = (*tempMap)["height"];

    setPaiBanFileList(m_seletePaiBanFileList);
}

void MsgControl::setOperatList(const QVariantList& list){
    int row = list.at(0).toInt();
    if(row < 0) return;

    QVariantMap* tempMap = (QVariantMap*)m_seletePaiBanFileList.at(row).data();
    QVariantList tempList = list[1].toList();
    const bool& extend = tempList.at(0).toBool();
    const int& rotation = tempList.at(1).toInt();
    const bool& origin = tempList.at(2).toBool();

    //设置旋转角度
    if(0 <= rotation){
        if(rotation != (*tempMap)["rotation"].toInt()){
            float w = (*tempMap)["width"].toFloat();
            float h = (*tempMap)["height"].toFloat();
            (*tempMap)["width"] = QString::number(h,'f',3);
            (*tempMap)["height"] = QString::number(w,'f',3);

            float w1 = (*tempMap)["originWidth"].toFloat();
            float h1 = (*tempMap)["originHeight"].toFloat();
            (*tempMap)["originWidth"] = QString::number(h1,'f',3);
            (*tempMap)["originHeight"] = QString::number(w1,'f',3);

            (*tempMap)["initScale"] = 1.0/ (*tempMap)["initScale"].toFloat();
        }
        (*tempMap)["rotation"] = rotation;
    }

    //设置是否自适应纸张宽度
    (*tempMap)["extend"] = extend;
    if(extend){
        QString tempPaperWidth = "";
        if("mm" == m_SizeUnit){
            tempPaperWidth = m_PaperWidth;
        }else{
            tempPaperWidth = QString::number(m_PaperWidth.toFloat() * 254 / 10);
        }
        (*tempMap)["width"]  = tempPaperWidth;
        (*tempMap)["height"] = QString::number(tempPaperWidth.toFloat() / (*tempMap)["initScale"].toFloat(),'f',3);
    }else{
        (*tempMap)["width"] = (*tempMap)["originWidth"];
        (*tempMap)["height"] = (*tempMap)["originHeight"];
    }

    //设置居中显示
    (*tempMap)["origin"] = origin;

    setPaiBanFileList(m_seletePaiBanFileList);
}

void MsgControl::motorMoveForward(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&,flag](){
        Json::Value root;
        root["button"] = "movebackward";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveBack(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "moveforward";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveLeft(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "moveleft";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveRight(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "moveright";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveOrigin(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "goorg";
        root["status"] = "click";
        return root;
    }();

    m_DoDataThread->sendMsg(QString::fromStdString(cppJson_To_String(root)).trimmed());
}

void MsgControl::startPrint(int status){
    switch (status) {
        case 1:{
            Json::Value root;
            root["command"] = "print_start";
            root["type"] = "print";
            root["data"] = [&](){
                Json::Value root;
                root["print_list"] = [&](){
                    Json::Value root;
                    root.append([&]{
                        Json::Value root;
                            root["uuid"] = m_PrintWorkUUId.toStdString();
                            root["modename"] = m_RipModeName.toStdString();
                            root["md5id"] = m_PrintWorkUUId.toStdString();
                            root["printcount"] = 1;
                        return root;}());
                    return root ;
                }();
                root["printmode"] = Json::Value("auto");
                return root;
            }();

            m_DoDataThread->sendMsg(QString::fromStdString(cppJson_To_String(root)).trimmed());
            this->setStartBtnStatus(1);
        }break;
        case 2: pausePrint();break;
        case 3: resumePrint();break;
    }
}

void MsgControl::pausePrint(){
    Json::Value root;
    root["command"] = "print_pause";
    root["data"] = Json::objectValue;
    root["type"] = "print";

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::resumePrint(){
    Json::Value root;
    root["command"] = "print_resume";
    root["data"] = Json::objectValue;
    root["type"] = "print";

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::cancelPrint(){
    if(m_IsCanceled){
        return;
    }

    Json::Value root;
    root["command"] = "print_cancel";
    root["data"] = Json::objectValue;
    root["type"] = "print";

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::clean(const int& mode){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "setCleanMode";
    root["data"] =[&](){
        Json::Value root;
        root["mode"] = mode;
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::testPrint(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "test";
        root["status"] = "click";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getPrintState(){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "print_status";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

/*void MsgControl::setTaskConfig(){

    if(1 != m_StartBtnStatus){
        startPrint(m_StartBtnStatus);
        return;
    }

    Json::Value root;
    root["command"] = "print_set_task_config";
    root["type"] = "print";
    root["data"] = [&](){
        Json::Value root;
        root["uuid"] = m_CurPrintWorkMap["uuid"].toString().toStdString();
        root["modename"] = [&]{
            QString modeName = SystemConfig::getInstance()->value("ripmodename/"+m_RipModeName,"LS720x1080 6PASS").toString();
            QString modeType = colorsEnum2Str(m_CurPrintWorkMap["colorCount"].toInt());
            return m_RipModeMap[modeType].toMap()[modeName].toString().toStdString();
        }();
        //root["printcopies"] = m_PrintCopies;
        root["xcopies"] = 1;
        root["xcopyspacing"] = 0.0;
        root["ycopies"] = 1;
        root["ycopyspacing"] = 0.0;
        //root["scale"] = m_ScaleValue * 100;
        //root["scaley"] = m_ScaleValue * 100;
        //root["rotate"] = m_RotateAngle;
        root["mirror"] = [&]{
            Json::Value root;
            root.append(m_RotateMap["horizen"]);
            root.append(m_RotateMap["vertical"]);
            return root;
        }();
        root["whiteink"] = [&]{
            Json::Value root;
            root.append([&]{
                Json::Value root;
                root["mode"] = SystemConfig::getInstance()->value("whiteinkmode/"+m_ThickNess,"smooth-invert").toString().toStdString();
                root["density"] = SystemConfig::getInstance()->value("whiteink/density","ownset").toString().toStdString();
                root["densityvalue"] = SystemConfig::getInstance()->value("whiteink/densityvalue",80.0).toFloat();
                return root;
            }());
            return root;
        }();
        return root;
    }();

    m_DoDataThread->sendMsg(QString::fromStdString(cppJson_To_String(root)).trimmed());
}*/

void MsgControl::getUSB_FileDir(){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "open_filesystem";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = "UPan";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getWifi_FileDir(){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "open_filesystem";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = "WiFiDir";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getForward_DirInfo(){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "filesystem_dirback";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getNext_DirInfo(const QString& name){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "get_filesystem_info";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = name.toStdString();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getWifiQrenCode(){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "get_hotspot_info";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}


void MsgControl::doNetConnect(const bool& flag){
    //连接服务端之后，立即获取目录 | 打印模式
    if(flag){
        setLanguage(m_Language);
        //getRipModeNameAlias();
        //getRipMode();
        getUSB_FileDir();
        getRipSetting();
        getWifiQrenCode();
        powerOnSelfCheck();
        //getRip_BoardVersion();
        //getPrintSetting();
        //getWifi_FileDir();
    }

    m_NetConnected = flag;
    emit netConnectedChanged();
}

void MsgControl::doPicCompleted(const std::map<QString,QString>& map){
    m_PicMd5StrMap = map;
}

void MsgControl::doDealCompleted1(){
    emit smallPicRefresh();
}

void MsgControl::doDealAutoPackCompleted(){
    //关闭等待对话框
    emit showWaitDia(false);
}

void MsgControl::doDealFixedPackCompleted(){
    preAddPrintWork(1);
}

void MsgControl::doUpdateUI_BigPicSize(const int& w,const int& h){
    emit setFinalBigPicSize(w,h);
}

void MsgControl::doCheckPackPaper(const bool& b){
    if(!b){
        QVariantMap msgMap;
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        if("en" == m_Language){
            msgMap["msg"]   = "Evcolor Can't be Empty!";
        }else{
            msgMap["msg"]   = "导入曲线不能为空!";
        }
        setErrorMsg(msgMap);
    }
}

void MsgControl::doDealBingPack(MtPackTransformRet * ret,const QList<int>& jobIndex){
    m_MtPack = ret;
    m_JobIndex = jobIndex;
}

//更新自动排版视图
void MsgControl::doDealAutoPackList(const QVariantList& list)
{
    emit refreshPackView(list);
}

void MsgControl::doDealPaperHeight(const double& height){
    setPaperHeight(QString::number(height));
}

void MsgControl::powerOnSelfCheck(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "poweronSelfcheck";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getRipMode(){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "ripserver_query_mode";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getRipModeNameAlias(){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "get_ripservermode_alias";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getPicinfo(const QString& filePath, const QString& uuid){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "ripserver_query_picinfo";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = filePath.toStdString();
        root["uuid"] = uuid.toStdString();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed(),true);
}

QVariantList MsgControl::buildRealPackListView(QVariantList& list,double& pH){
    if(list.isEmpty()) return {};

    double p_w = 0;
    if("inch" == m_SizeUnit){
        p_w = m_PaperWidth.toDouble() * 254/10;
    }else{
        p_w = m_PaperWidth.toDouble();
    }

    double x_Axis = 0,y_Axis = 0;
    QVariantList tempList = {};
    for(int jobInx = 0; jobInx < list.size(); jobInx++){
        //判断是否自适应纸张宽度
        QVariantMap* tempMap = (QVariantMap*)list.at(jobInx).data();
        if((*tempMap)["extend"].toBool()){
            QString tempPaperWidth = "";
            if("mm" == m_SizeUnit){
                tempPaperWidth = m_PaperWidth;
            }else{
                tempPaperWidth = QString::number(m_PaperWidth.toFloat() * 254 / 10);
            }
            (*tempMap)["width"]  = tempPaperWidth;
            (*tempMap)["height"] = QString::number(tempPaperWidth.toFloat() / (*tempMap)["initScale"].toFloat(),'f',3);
        }else{
            (*tempMap)["width"] = (*tempMap)["originWidth"];
            (*tempMap)["height"] = (*tempMap)["originHeight"];
        }

        int copy = list.at(jobInx).toMap()["copy"].toInt();
        double imageHeight  = list.at(jobInx).toMap()["height"].toDouble();
        double imageWidth   = list.at(jobInx).toMap()["width"].toDouble();
        double implicitWidth = list.at(jobInx).toMap()["width"].toDouble() + m_PictureGap;
        double implicitHeight = imageHeight + m_PictureGap;
        bool isOrigin = list.at(jobInx).toMap()["origin"].toBool();
        int col = qCeil((double)p_w / implicitWidth);
        if((col*implicitWidth - m_PictureGap) > p_w ){
            col-=1;
            if(col <= 0) col = 1;
        }

        //计算一个job可以排列几行
        int row =  qCeil((double)copy / col);
        //计算最终的高
        pH += implicitHeight * row;

        QString fileName = list.at(jobInx).toMap()["filePath"].toString();
        double initWidth = 0,initHeight = 0,scale = 1;
        double xDpi = 0,yDpi = 0;
        bool isRotate = false;
        int rotation = list.at(jobInx).toMap()["rotation"].toInt();
        if(0 == rotation || 180 == rotation ){
            scale  = list.at(jobInx).toMap()["width"].toDouble()*1.0 / list.at(jobInx).toMap()["initWidth"].toDouble();
            isRotate = false;
        }else{
            scale  = list.at(jobInx).toMap()["height"].toDouble()*1.0 / list.at(jobInx).toMap()["initWidth"].toDouble();
            isRotate = true;
        }

        initWidth = list.at(jobInx).toMap()["initWidth"].toDouble();
        initHeight = list.at(jobInx).toMap()["initHeight"].toDouble();
        xDpi = list.at(jobInx).toMap()["xDpi"].toDouble();
        yDpi = list.at(jobInx).toMap()["yDpi"].toDouble();

        int leftObj = copy % col;
        int relColumn =  copy <= col ? copy : col;
        double origin_Axis = 0;
        if(isOrigin){
            origin_Axis = (p_w - (relColumn*implicitWidth - m_PictureGap))/2;
        }else{
            origin_Axis = 0;
        }

        for(int i = 0 ; i < row ; i++){
            for(int j = 0 ; j < col ; j++){
                if(j < col){
                    x_Axis = origin_Axis + (implicitWidth)*j;
                }

                if(i+1 == row){
                    if(leftObj > 0 && j+1 > leftObj){
                        continue;
                    }
                }
                QVariantMap tempMap;
                tempMap["initWidth"] = initWidth;
                tempMap["initHeight"] = initHeight;
                tempMap["width"] = imageWidth;
                tempMap["height"] = imageHeight;
                tempMap["x"] = x_Axis;
                tempMap["y"] = y_Axis;
                tempMap["xDpi"] = xDpi;
                tempMap["yDpi"] = yDpi;
                tempMap["scale"] = scale;
                tempMap["isRotate"] = isRotate;
                tempMap["jobIndex"] = jobInx;
                tempMap["fileName"] = fileName;
                tempMap["rotation"] = rotation;

                tempList << tempMap;
            }

            if(i+1 != row){
                y_Axis += (imageHeight + m_PictureGap);
            }
        }
        y_Axis += (imageHeight + m_PictureGap);
    }
    pH -= m_PictureGap;

    return tempList;
}

void MsgControl::initPrintState(){
    m_SelectedFilesList.clear();
    m_seletePaiBanFileList.clear();
    m_FileInfoMap.clear();
    setPrintBarShow(false);
    setStartBtnStatus(1); //重置按钮状态
    setBingPack(false);//更新视图
    //emit paiBanFileListChanged();
}

QString MsgControl::colorsEnum2Str(const int& colorCount){
    QString res = "CMYK";
    switch (colorCount) {
        case (int)ColorsEnum::COLOR:;
        case (int)ColorsEnum::COLOR_16:;
        case (int)ColorsEnum::COLOR_256:;
        case (int)ColorsEnum::COLOR_GRAY:;
        case (int)ColorsEnum::COLOR_RGB:res = "CMYK";break;
        case (int)ColorsEnum::COLOR_RGB_O:res = "CMYKW1";break;
        case (int)ColorsEnum::COLOR_CYMK:res = "CMYK";break;
        case (int)ColorsEnum::COLOR_CYMK_O:res = "CMYKW1";break;
        case (int)ColorsEnum::COLOR_LAB:res = "CMYK";break;
        case (int)ColorsEnum::COLOR_LAB_O:res = "CMYKW1";break;
        default:break;
    }
    return res;
}

QString MsgControl::printButtonEnum2Str(const int& button){
    QString res = "nozzleState";
    switch (button) {
        case (int)PrintButtonEnum::nozzleState: res = "nozzleState";break;
        case (int)PrintButtonEnum::verticalCalibration: res = "verticalCalibration";break;
        case (int)PrintButtonEnum::stepCalibration: res = "stepCalibration";break;
        case (int)PrintButtonEnum::horizontalCalibration: res = "horizontalCalibration";break;
        case (int)PrintButtonEnum::sameColorCalibration:res = "sameColorCalibration";break;
        case (int)PrintButtonEnum::colorCalibration:res = "colorCalibration";break;
        case (int)PrintButtonEnum::whiteColorCalibration:res = "whiteColorCalibration";break;
        case (int)PrintButtonEnum::doubleDirCalibration:res = "doubleDirCalibration";break;
        case (int)PrintButtonEnum::GearRatioCalibration:res = "GearRatioCalibration";break;
        default:break;
    }
    return res;
}

void MsgControl::setLanguage(const QString& type){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "setLanguage";
    root["data"] = [&](){
        Json::Value root;
        if("en" == type)
            root["language"] = 31;// cn->25 | en->31
        else
            root["language"] = 25;// cn->25 | en->31
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());

    //设置语言
    m_Language = type;
    emit changeLanguage(type);
}

void MsgControl::importEvcolor(const QString &path){
    if(path.isEmpty()) {
        QVariantMap msgMap;
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        if("en" == m_Language){
            msgMap["msg"]   = "Evcolor Can't be Empty!";
        }else{
            msgMap["msg"]   = "导入曲线不能为空!";
        }
        setErrorMsg(msgMap);
        return;
    }

    Json::Value root;
    root["type"] = "print";
    root["command"] = "import_icc_profile";
    root["data"] = [&](){
        Json::Value root;
        root["file"] = path.toStdString();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::exportEvcolor(const QString &path){
    if(path.isEmpty()) {
        QVariantMap msgMap;
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        if("en" == m_Language){
            msgMap["msg"]   = "Evcolor Can't be Empty!";
        }else{
            msgMap["msg"]   = "导出曲线不能为空!";
        }
        setErrorMsg(msgMap);
        return;
    }

    Json::Value root;
    root["type"] = "print";
    root["command"] = "export_icc_profile";
    root["data"] = [&](){
        Json::Value root;
        root["file"] = path.toStdString();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::addPrintWork(){
    if(m_RipModeName.isEmpty()){
        QVariantMap msgMap;
        msgMap["flag"] = true;
        if("en" == m_Language){
            msgMap["msg"]   = "Error,Evcolor is Empty!";
        }else{
            msgMap["msg"]   = "错误，获取的打印曲线为空!";
        }

        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
        return;
    }

    if(!m_MtPack) return;

    //uuid
    m_PrintWorkUUId = QString::number(QDateTime::currentDateTime().toTime_t());
    //添加打印任务
    Json::Value root;
    root["command"] = "print_list_add";
    root["type"] = "print";
    root["data"] = [&](){
        Json::Value root;
        root["add_list"] = [&](){
            Json::Value root;
            root.append([&]{
                Json::Value root;
                root["uuid"] = m_PrintWorkUUId.toStdString();
                root["modename"] = m_RipModeName.toStdString();
                root["printcount"] = 1;
                root["xcopies"] = 1;
                root["xcopyspacing"] = 0.0;
                root["ycopies"] = 1;
                root["ycopyspacing"] = 0.0;
                root["scale"] = 100.0;
                root["scaley"] = 100.0;
                root["rotate"] = 0;
                root["mirror"] = [&]{
                    Json::Value root;
                    root.append(false);
                    root.append(false);
                    return root;
                }();

                //设置白墨
                root["whiteink"] = [&]{
                    Json::Value root;
                    root.append([&]{
                        Json::Value root;
                        QString tempColor = m_InkStringList.at(m_InkList[0].toInt());
                        root["mode"] = tempColor.toStdString();
                        root["invert"] = false;
                        root["inkName"] = "W1";
                        return root;
                    }());
                    return root;
                }();

                //设置白墨内缩、外阔
                root["inkIE"] = [&]{
                    Json::Value root;
                    root.append([&]{
                        Json::Value root;
                        root["mode"] = m_InkStyleList.at(m_InkList[1].toInt()).toStdString();
                        root["index"] = 4;
                        root["dots"] = [&]{
                            Json::Value root;
                            if("mm" == m_SizeUnit){
                                root.append(m_InkList[5].toDouble()); //右
                                root.append(m_InkList[4].toDouble()); //下
                                root.append(m_InkList[3].toDouble()); //左
                                root.append(m_InkList[2].toDouble()); //上
                            }else{
                                root.append(m_InkList[5].toDouble()*254/10); //右
                                root.append(m_InkList[4].toDouble()*254/10); //下
                                root.append(m_InkList[3].toDouble()*254/10); //左
                                root.append(m_InkList[2].toDouble()*254/10); //上
                            }

                            //root.append(m_InkList[2].toDouble()); //上
                            //root.append(m_InkList[3].toDouble()); //左
                            //root.append(m_InkList[4].toDouble()); //下
                            //root.append(m_InkList[5].toDouble()); //右
                            return root;
                        }();
                        return root;
                    }());
                    return root;
                }();

                //设置view范围
                root["view"] = [&]{
                    Json::Value root;
                    root["left"]   = m_MtPack->view.left;
                    root["top"]    = m_MtPack->view.top;
                    root["right"]  = m_MtPack->view.right;
                    root["bottom"] = m_MtPack->view.bottom;
                    root["xdpi"]   = m_MtPack->view.xdpi;
                    root["ydpi"]   = m_MtPack->view.ydpi;
                    return root;
                }();

                //设置docs
                root["docs"] = [&]{
                    Json::Value root;
                    for(size_t i = 0; i < m_MtPack ->matCount; i ++)
                    {
                        auto *mat    = m_MtPack->matrix + i;
                        root.append([&]{
                            Json::Value root;
                            root["name"] = m_seletePaiBanFileList.at(m_JobIndex[i]).toMap()["filePath"].toString().toStdString().data();
                            root["password"] = "";
                            root["type"] = "";
                            root["colored"] = false;
                            root["imageBufferSize"] = 400*1024*1024;

                            root["transform"] = [&]{
                                Json::Value root;
                                if(qAbs(mat->a) < 0.00001)
                                    root["a"]  = 0;
                                else
                                    root["a"]  = mat->a;

                                root["b"]  = mat->b;
                                root["c"]  = mat->c;

                                if(qAbs(mat->d) < 0.00001)
                                    root["d"]  = 0;
                                else
                                    root["d"]  = mat->d;

                                root["tx"] = mat->tx;
                                root["ty"] = mat->ty;
                                return root;
                            }();

                            //设置白墨
                            root["whiteInks"] = [&]{
                                Json::Value root;
                                root.append([&]{
                                    Json::Value root;
                                    QString tempColor = m_InkStringList.at(m_InkList[0].toInt());
                                    root["mode"] = tempColor.toStdString();
                                    root["invert"] = false;
                                    root["inkName"] = "W1";
                                    return root;
                                }());
                                return root;
                            }();

                            return root;
                        }());
                    }

                    return root;
                }();

                return root;
            }());
            return root ;
        }();
        return root;
    }();

    m_DoDataThread->sendMsg(QString::fromStdString(cppJson_To_String(root)).trimmed());
    //释放内存
    MtPackTransformRelease(m_MtPack); //释放排版转换器
    m_MtPack = nullptr;
    m_JobIndex.clear();
}

void MsgControl::removeExistedPrintWorks(){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "print_list_clear";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::sysexit(){
    QJsonObject root;
    QJsonObject data;
    root.insert("type","system");
    root.insert("command","exit");
    root.insert("data",data);
    QJsonDocument doc;
    doc.setObject(root);
    QUdpSocket udp_server;
    udp_server.abort();
    udp_server.open(QIODevice::ReadWrite);
    QString str= QString(doc.toJson(QJsonDocument::Compact));
    udp_server.connectToHost(QHostAddress("127.0.0.1"),26678);
    udp_server.write(str.toUtf8());
    udp_server.abort();
}

QString MsgControl::getSoftWareVersion(){
    return m_SoftWareVersion;
}

void MsgControl::getRip_BoardVersion(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "getBoardVersion";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::printSetting(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "open_sysSettingUI";
    root["data"] = []{
        Json::Value root;
        root["password"] = "123";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::setPaperWidth(const QString &paperWidth){
    //if(paperWidth == m_PaperWidth) return;

    QVariantMap msgMap;
    float p_w = paperWidth.toFloat();

    if(p_w <= 0)
    {
        msgMap["flag"] = true;
        if("en" == m_Language){
            msgMap["msg"]   = "PaperWidth cannot be or below 0 !";
        }else{
            msgMap["msg"]   = "纸宽不能小于零!";
        }
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);

        if("mm" == m_SizeUnit){
            m_PaperWidth = "610";
            emit paperWidthChanged();
            emit onSetPaperWidth(m_PaperWidth);
            SystemConfig::getInstance()->setValue("setting/paperwidth",m_PaperWidth);
        }else{
            m_PaperWidth = "24.016";
            emit paperWidthChanged();
            emit onSetPaperWidth(QString::number(m_PaperWidth.toFloat() * 254/10,'f',3));
            SystemConfig::getInstance()->setValue("setting/paperwidth",m_PaperWidth.toFloat() * 254/10);
        }
        return;
    }

    if("mm" == m_SizeUnit){
        if(p_w > 610){
            msgMap["flag"] = true;
            if("en" == m_Language){
                msgMap["msg"]   = "PaperWidth is oversize !";
            }else{
                msgMap["msg"]   = "纸宽超过最大限宽!";
            }
            msgMap["type"]  = "error";
            this->setErrorMsg(msgMap);

            m_PaperWidth = "610";
            emit paperWidthChanged();
            emit onSetPaperWidth(m_PaperWidth);
        }else{
            if(p_w > 609.99)
                m_PaperWidth = "610";
            else
                m_PaperWidth = paperWidth;

            emit paperWidthChanged();
            emit onSetPaperWidth(m_PaperWidth);
        }
        SystemConfig::getInstance()->setValue("setting/paperwidth",m_PaperWidth);
    }else{
        if(p_w > 24.016){
            msgMap["flag"] = true;
            if("en" == m_Language){
                msgMap["msg"]   = "PaperWidth is oversize !";
            }else{
                msgMap["msg"]   = "纸宽超过最大限宽!";
            }
            msgMap["type"]  = "error";
            this->setErrorMsg(msgMap);

            m_PaperWidth = "24.016";
            emit paperWidthChanged();
            emit onSetPaperWidth(QString::number(m_PaperWidth.toFloat() * 254/10,'f',3));
        }else{
            m_PaperWidth = paperWidth;
            emit paperWidthChanged();
            emit onSetPaperWidth(QString::number(m_PaperWidth.toFloat() * 254/10,'f',3));
        }
        SystemConfig::getInstance()->setValue("setting/paperwidth",m_PaperWidth.toFloat() * 254/10);
    }

    //纸张宽幅改变，立即重新排版一次
    setPaiBanFileList(m_seletePaiBanFileList);
}

QString MsgControl::getPaperWidth(){
   return m_PaperWidth;
}

void MsgControl::setPaperHeight(const QString &paperHeight){
    m_PaperHeight = paperHeight;
    emit paperHeightChanged();
}

QString MsgControl::getPaperHeight(){
    return m_PaperHeight;
}

//注意* 打印时候先获取打印驱动的输出宽幅
void MsgControl::setStartGenerateBigPic(const bool &){
    QVariantMap msgMap;
    if(m_seletePaiBanFileList.size() <= 0) {
        msgMap["flag"] = true;
        if("en" == m_Language){
            msgMap["msg"]   = "Please add print work!";
        }else{
            msgMap["msg"]   = "请添加打印任务!";
        }
        msgMap["type"]  = "tip";
        this->setErrorMsg(msgMap);
        return;
    }

    isCheckMachineOutWidth = true;
    getPrintDriverSetting();
}

QVariantMap MsgControl::getBoardVersion(){
    return m_BoardVersionMap;
}

void MsgControl::setBoardVersion(const QVariantMap & versionMap){
    m_BoardVersionMap = versionMap;
    emit boardVersionChanged();
}

void MsgControl::setSizeUnit(const QString &unit){
    m_SizeUnit = unit;
    QString tempPaperHeight = "0";
    if("mm" == m_SizeUnit){
        m_PaperWidth = QString::number(m_PaperWidth.toFloat() * 254 / 10,'f',2);
    }else{
        m_PaperWidth = QString::number(m_PaperWidth.toFloat() * 10 / 254,'f',3);
    }

    setPaperWidth(m_PaperWidth);
    setPaperHeight(m_PaperHeight);
    emit sizeUnitChanged();
}

QString MsgControl::getSizeUnit(){
    return m_SizeUnit;
}

void MsgControl::setQualityMode(const QVariantMap &list){
    m_QualityModeList = list;
    emit qualityModeChanged();
}

QVariantMap MsgControl::getQualityMode(){
    return m_QualityModeList;
}

void MsgControl::setPrintPaperStyle(const QVariantList &list){
    m_PrintPaperStyle = list;
    emit printPaperStyleChanged();
}

QVariantList MsgControl::getPrintPaperStyle(){
    return m_PrintPaperStyle;
}

void MsgControl::setPaperAndEcolor(const QVariantList &list){
   if(m_PrintPaperStyle.isEmpty()) return;

   QString paperStyle = m_PrintPaperStyle[list[0].toInt()].toString();
   QString ecolorLine = m_QualityModeList[paperStyle].toList().at(list[1].toInt()).toString();

   m_RipModeName = m_FinalEcolorLine[paperStyle+" "+ecolorLine];
}

void MsgControl::setInkSetting(const QVariantList &list){
    if(list.size() < 6 || list.isEmpty())
        return;

    m_InkList = list;
    SystemConfig::getInstance()->setValue("setting/inkSetting",m_InkList);
    emit inkSettingChanged();
}

QVariantList MsgControl::getInkSetting(){
    return m_InkList;
}

void MsgControl::setPrintDriverSetting(const QVariantList &list){
    if(list.size() < 14) return;
    m_PrintSetting.PrintStartPositionMM =   list[0].toDouble();
    m_PrintSetting.PaperWidth =             list[1].toDouble();
    m_PrintSetting.PrintSpeedSelect =       list[2].toUInt();
    m_PrintSetting.PrintDirectionSelect =   list[3].toUInt();
    m_PrintSetting.PrintFeatherEnable =     list[4].toInt();
    m_PrintSetting.bFlashBeforePrint =      list[5].toInt();
    m_PrintSetting.PrintFeatherSelect =     list[6].toUInt();
    m_PrintSetting.PrintFeatherPercent[0] = list[7].toList().at(0).toInt();
    m_PrintSetting.PrintFeatherPercent[1] = list[7].toList().at(1).toInt();
    m_PrintSetting.bColorBarEnable =        list[8].toInt();
    m_PrintSetting.ColorBarSelect =         list[9].toInt();
    m_PrintSetting.ColorBarWidth =          list[10].toDouble();
    m_PrintSetting.ColorBarGap =            list[11].toDouble();
    m_PrintSetting.ColorBarConcPercentage = list[12].toDouble();
    m_PrintSetting.bUseCutter             = list[13].toInt();
}

void MsgControl::setPenTouCanShu(const QVariantList &list){
    if(list.size() < 7) return;
    m_NozzlCalibrate.calibrationMaterial        = list[0].toInt();
    m_NozzlCalibrate.calibrationXDpi            = list[1].toInt();
    m_NozzlCalibrate.calibrationSpeed           = list[2].toInt();
    m_NozzlCalibrate.calibrationPrintWidth      = list[3].toDouble();

    //喷头废孔
    int machineGroupNumber = m_NozzlCalibrate.machineGroupNumber;
    int oneGroupNozzleNumber = m_NozzlCalibrate.oneGroupNozzleNumber;
    int uiParam[BOOLEAN_MAX_NUMBER][machineGroupNumber][oneGroupNozzleNumber];
    for(int i = 0; i < BOOLEAN_MAX_NUMBER; i++)
    {
        for(int j = 0 ; j < machineGroupNumber;j++)
        {
            for(int k = 0 ; k < m_NozzlCalibrate.oneGroupNozzleNumber ;k++){
                uiParam[i][j][k] = list[4].toList()[i].toList()[k].toInt();
            }
        }
    }

    for(int i = 0; i < BOOLEAN_MAX_NUMBER; i++)
    {
         for(uint32_t iGroup = 0; iGroup < m_NozzlCalibrate.machineGroupNumber; iGroup++)
         {
             for(uint32_t iColor = 0; iColor < m_NozzlCalibrate.machineColorNumber; iColor++)
             {
                 //第iGroup组第(iColor / config.m_OneNozzleColorNumber)喷头,i(0-前废孔，1-后废孔)参数填入数组
                 m_NozzlCalibrate.invalidNozzleNumber[iColor][iGroup][i] =
                         uiParam[i][iGroup][iColor / m_NozzlCalibrate.oneNozzleColorNumber];
             }
         }
    }


//    //横向组间距
//    int uiParam1[BOOLEAN_MAX_NUMBER][machineGroupNumber][oneGroupNozzleNumber];
//    for(int i = 0; i < BOOLEAN_MAX_NUMBER; i++)
//    {
//         for(uint32_t iGroup = 0; iGroup < m_NozzlCalibrate.machineGroupNumber; iGroup++)
//         {
//             for(int iColorGroup = 0; iColorGroup < m_NozzlCalibrate.oneGroupNozzleNumber; iColorGroup++)
//             {
//                 //if((int)iColorGroup > list[5].toList().size()-1) break;
//                 //m_NozzlCalibrate.horzGroupSpacing[i][m_NozzlCalibrate.calibrationXDpi][m_NozzlCalibrate.calibrationSpeed][iGroup][iColorGroup] =
//                  //       list[5].toList()[i].toList()[iColorGroup].toInt();
//                 //qDebug() << m_NozzlCalibrate.horzGroupSpacing[i][m_NozzlCalibrate.calibrationXDpi][m_NozzlCalibrate.calibrationSpeed][iGroup][iColorGroup];
//             }
//         }
//     }

    //双向套色
    for(uint32_t iGroup = 0; iGroup < m_NozzlCalibrate.machineGroupNumber; iGroup++)
    {
        for(uint32_t iColor = 0; iColor < m_NozzlCalibrate.machineColorNumber; iColor++)
        {
            m_NozzlCalibrate.doubleNozzleOffset[m_NozzlCalibrate.calibrationMaterial][m_NozzlCalibrate.calibrationXDpi][m_NozzlCalibrate.calibrationSpeed][iColor][iGroup]
             = list[6].toList()[iColor / m_NozzlCalibrate.oneNozzleColorNumber].toInt();
        }
    }
}

void MsgControl::setAdjustPixel(const int &pixel){
    m_NozzleCaliTest.adjustPixel = pixel;
}

void MsgControl::setJiZhunTaoSe(const QVariantList& list){
    //基准套色
    for (int i = 0; i < BOOLEAN_MAX_NUMBER; i++)
    {
        for(uint32_t iGroup = 0; iGroup < m_NozzlCalibrate.machineGroupNumber; iGroup++)
        {
            for(uint32_t iColor = 0; iColor < m_NozzlCalibrate.machineColorNumber; iColor++)
            {
                m_NozzlCalibrate.baseNozzleOffset[i][m_NozzlCalibrate.calibrationXDpi][iColor][iGroup]
                  = list[i].toList()[iColor].toInt();
            }
        }
    }
}

void MsgControl::setZuNeiTaoSe(const QVariantList& list){
    //组内套色
    for(int i = m_NozzlCalibrate.oneNozzleColorNumber; i < m_NozzlCalibrate.oneNozzleColorNumber * m_NozzlCalibrate.oneGroupNozzleNumber; i++)
    {
        m_NozzlCalibrate.horzGroupsOffset[m_NozzlCalibrate.calibrationXDpi][i] = list[0].toInt();
        m_NozzlCalibrate.stepAdjustOffset[i] =  list[1].toInt();
    }
}

void MsgControl::setTempBoardPara(const QVariantList& list ){
    if(5 > list.size()) return;

    m_TempBoardAllPARAM.frontHeatTemp = list.at(0).toInt();
    m_TempBoardAllPARAM.middleHeatTemp = list.at(1).toInt();
    m_TempBoardAllPARAM.rearHeatTemp = list.at(2).toInt();
    m_TempBoardAllPARAM.fanGear = list.at(3).toInt();
    m_TempBoardAllPARAM.lightState = list.at(4).toInt();
}

void MsgControl::setTaiBanPara(const QVariantList &list){
    if(list.size() < 3 || m_PlatformsList.size() <= 0) return;

    int row = list.at(0).toInt();
    int col = list.at(1).toInt();

    QVariantMap* tempMap = (QVariantMap*)m_PlatformsList.at(row).data();

    switch (col){
        case 0:(*tempMap)["platName"] = list.at(2).toString();break;
        case 1:(*tempMap)["width"] = list.at(2).toFloat();break;
        case 2:(*tempMap)["height"] = list.at(2).toFloat();break;
        case 3:(*tempMap)["xPos"] = list.at(2).toFloat();break;
        case 4:(*tempMap)["yPos"] = list.at(2).toFloat();break;
    }

    if(0 == col){
        m_PlatformNameList.replace(row,list.at(2).toString());
    }

    emit taiBanList(m_PlatformNameList,m_PlatformsList,m_PlatformsPARAM.platformOrgToPrintDistance);
}

void MsgControl::settaiBanTypeDis(const QVariantList& list){
    if(list.size() < 2){
        return;
    }

    m_PlatformsPARAM.platformUseIndex = list.at(0).toInt();
    m_PlatformsPARAM.platformOrgToPrintDistance = list.at(1).toFloat();
}

void MsgControl::setFileSelected(const QString & file, const bool &b){
    if(file.isEmpty()) return;
    m_SeletcedFileMap[file] = b;
}

bool MsgControl::getFileSelected(const QString &file){
    return m_SeletcedFileMap[file];
}

void MsgControl::clearSeletedFileList(){
    m_SelectedFilesList.clear();
}

void MsgControl::addPaiBanFileList(){
    QVariantMap msgMap;
    msgMap["flag"]  = "false";
    msgMap["type"]  = "error";
    if(1 != m_StartBtnStatus){
        if("en" == m_Language){
            msgMap["msg"] = "Printing... ,mustn't add files!";
        }else{
            msgMap["msg"] = "打印中...,禁止添加文件!";
        }
        setErrorMsg(msgMap);
        setSelectPicture(false);
        return;
    }
    if(m_SelectedFilesList.empty()) {
        if("en" == m_Language){
            msgMap["msg"] = " Selected files can't empty,or unsupport format Image!";
        }else{
            msgMap["msg"] = "添加文件不能为空,或者图片格式不支持!";
        }
        setErrorMsg(msgMap);
        setSelectPicture(false);
        return;
    }

    int jobIndex = m_seletePaiBanFileList.size() - 1;

    for(const auto& fileSource : m_SelectedFilesList){
        QVariantMap map;
        map["filePath"] = fileSource;
        map["uuid"] = m_PicMd5StrMap[fileSource]; //图片全路径

        float w = m_FileInfoMap[fileSource]["width"].toFloat();//图片宽度
        float h = m_FileInfoMap[fileSource]["height"].toFloat();//图片高度

        //过滤不支持的格式
        if(0 == w || 0 == h){
            m_SelectedFilesList.removeOne(fileSource);
            continue;
        }

        //任务job索引
        jobIndex+=1;
        map["jobIndex"] = jobIndex; //所属job的索引
        map["width"] = QString::number(w, 'f', 3);
        map["height"] = QString::number(h, 'f', 3);
        map["initWidth"] = QString::number(w, 'f', 3);
        map["initHeight"] = QString::number(h, 'f', 3);
        map["originWidth"] = QString::number(w, 'f', 3);
        map["originHeight"] = QString::number(h, 'f', 3);
        map["initScale"] = (float)(w / h);
        map["xDpi"] = m_FileInfoMap[fileSource]["xdpi"];
        map["yDpi"] = m_FileInfoMap[fileSource]["ydpi"];
        map["copy"] = 1;                //初始份数
        map["extend"] = false;
        map["rotation"] = 0;
        map["origin"] = false;
        map["x"] = 0.00;
        map["y"] = 0.00;

        m_seletePaiBanFileList << map;
    }

    if(m_SelectedFilesList.size() > 0){
        emit pageChanged(2);
        setPaiBanFileList(m_seletePaiBanFileList);
    }else{
        if("en" == m_Language){
            msgMap["msg"] = "Unsupport format Image!";
        }else{
            msgMap["msg"] = "图片的格式不支持!";
        }
        setErrorMsg(msgMap);
        setSelectPicture(false);
    }
}

void MsgControl::deletePaiBanFileList(const int &row){
    if(m_seletePaiBanFileList.empty() || -1 == row) return;
    m_seletePaiBanFileList.removeAt(row);

    m_CurrentPicIndex = -1;

    if(0 >= m_seletePaiBanFileList.size())
        setBingPack(false);

    //统计删除之后，排版显示区域移动到的索引位置
    for(int i = 0 ; i < row;i++)
    {
        m_CurrentPicIndex += m_seletePaiBanFileList.at(i).toMap()["copy"].toInt();
    }

    setPaiBanFileList(m_seletePaiBanFileList);
}

QString MsgControl::getIconUUId(const QString &absPath){
    return m_PicMd5StrMap[absPath];
}

void MsgControl::setRecoverButtonState(const bool &flag){
    emit recoverButtonState(flag);
}

int MsgControl::getSytemCPU_Counts(){
    return  QThread::idealThreadCount();
}

void MsgControl::setRIPThreads(const int &count){
    m_RIPThreads = count;
    SystemConfig::getInstance()->setValue("setting/ripThreads",m_RIPThreads);
    getRipSetting();
}

int MsgControl::getRIPThreads(){
    return m_RIPThreads;
}

void MsgControl::setUnit(const QString &unit){
    m_SizeUnit = unit;
    SystemConfig::getInstance()->setValue("setting/sizeunit",m_SizeUnit);
    setSizeUnit(unit);
}

QString MsgControl::getSizeInitUnit(){
    return m_SizeUnit;
}

QString MsgControl::getInitLanguage(){
    return m_Language;
}

void MsgControl::setBingPack(const bool &b){
    isAutoBingPack = b;
    emit bingPackChanged();

    //1. 通知dealpicturethread修改排版状态指
    emit onBingPack(b);
    //2. 确保信号发出，状态已经更新之后，再进行排版
    QThread::msleep(10);
    //3. 分情况更新UI
    if(b){
        // 自动 | 通知进行一次排版计算
        emit onGetBigPic(m_seletePaiBanFileList);
        //开始等待...
        emit showWaitDia(true);
    }else{
        // 恢复固定排版
        setPaiBanFileList(m_seletePaiBanFileList);
    }
}

bool MsgControl::getBingPack(){
    return isAutoBingPack;
}

void MsgControl::saveConfigureFile(const int & page){
    switch (page) {
        case 0: savePrintDriverSetting();break;
        case 1: savaPenTouJiaoZhun();break;
        case 2: saveTempBoardSetting();break;
        case 3: saveTaiBanSetting();break;
        default:break;
    }
}

void MsgControl::getPrintDriverSetting(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "getCommonPrintSetting";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::savePrintDriverSetting(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "saveCommonPrintSetting";
    root["data"] = [&]{
        Json::Value root;
        root["struct"] = [&]{
            Json::Value root;
            Json::Reader reader;
            const std::string json_str = xpack::json::encode(m_PrintSetting); 
            if(!reader.parse(json_str, root)) {
                return root = Json::objectValue;
            }
            return root;
        }();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getPenTouJiaoZhun(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "nozzleCalibrationParam";
    root["data"] = [&]{
        Json::Value root;
        root["status"] = "get";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::savaPenTouJiaoZhun(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "nozzleCalibrationParam";
    root["data"] = [&]{
        Json::Value root;
        root["status"] = "set";
        root["struct"] = [&]{
            Json::Value root;
            Json::Reader reader;
            const std::string json_str = xpack::json::encode(m_NozzlCalibrate);
            if(!reader.parse(json_str, root)) {
                return root = Json::objectValue;
            }
            return root;
        }();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::saveTempBoardSetting(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "setTempBoardParam";
    root["data"] = [&]{
        Json::Value root;
        Json::Reader reader;
        const std::string json_str = xpack::json::encode(m_TempBoardAllPARAM);
        if(!reader.parse(json_str, root)) {
            return root = Json::objectValue;
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getTempBoardSetting(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "getTempBoardParam";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getTaiBanSetting(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "getPlatformParam";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::saveTaiBanSetting(){
    m_PlatformsPARAM.bUsePlatform = true;
    m_PlatformsPARAM.platformNum  = m_PlatformNameList.size();
    for(int i = 0; i < m_PlatformNameList.size(); i++){
        memcpy(m_PlatformsPARAM.platformsSetParam[i].platName,
                m_PlatformNameList[i].toString().toUtf8().data(),
                m_PlatformNameList[i].toString().toUtf8().size()+1);
        m_PlatformsPARAM.platformsSetParam[i].width = m_PlatformsList.at(i).toMap()["width"].toFloat();
        m_PlatformsPARAM.platformsSetParam[i].height = m_PlatformsList.at(i).toMap()["height"].toFloat();
        m_PlatformsPARAM.platformsSetParam[i].xPos = m_PlatformsList.at(i).toMap()["xPos"].toFloat();
        m_PlatformsPARAM.platformsSetParam[i].yPos = m_PlatformsList.at(i).toMap()["yPos"].toFloat();
    }

    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "setPlatformParam";
    root["data"] = [&]{
        Json::Value root;
        root["parms"] = [&]{
            Json::Value root;
            Json::Reader reader;
            const std::string json_str = xpack::json::encode(m_PlatformsPARAM);
            if(!reader.parse(json_str, root)) {
                return root = Json::objectValue;
            }
            return root;
        }();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::addTaiBan(){
    if(m_PlatformNameList.size() > 4){
        QVariantMap msgMap;
        msgMap["msg"]   = "";
        msgMap["flag"]  = true;

        if("en" == m_Language){
            msgMap["msg"]  = "Platforms cant't be over 5!";
        }else{
            msgMap["msg"]  = "台板数不能大于5个";
        }
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
        return;
    }

    QVariantMap innerMap;
    innerMap["platName"] = "null";
    innerMap["width"] = 0;
    innerMap["height"] = 0;
    innerMap["xPos"] = 0;
    innerMap["yPos"] = 0;
    m_PlatformNameList << "null";
    m_PlatformsList << innerMap;

    emit taiBanList(m_PlatformNameList,m_PlatformsList,m_PlatformsPARAM.platformOrgToPrintDistance);
}

void MsgControl::deleteTaiban(const int& index){
    m_PlatformNameList.removeAt(index);
    m_PlatformsList.removeAt(index);

    emit taiBanList(m_PlatformNameList,m_PlatformsList,m_PlatformsPARAM.platformOrgToPrintDistance);
}

void MsgControl::excuteTaiBan(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "platformBtnClicked";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::nozzleCalibrationTest(const int& dir, const int& button){
    m_NozzleCaliTest.printDir = dir;
    m_NozzleCaliTest.printWidth = m_NozzlCalibrate.calibrationPrintWidth;
    m_NozzleCaliTest.printDpi = m_PrintJingDuList[m_NozzlCalibrate.calibrationXDpi];

    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "nozzleCalibrationTestImage";
    root["data"] = [&]{
        Json::Value root;
        root["button"] = printButtonEnum2Str(button).toStdString();
        root["struct"] = [&]{
            Json::Value root;
            Json::Reader reader;
            const std::string json_str = xpack::json::encode(m_NozzleCaliTest);
            if(!reader.parse(json_str, root)){
                return root = Json::objectValue;
            }
            return root;
        }();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::injectInk(const QString &during){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "injectink";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::stopInjectInk(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "stopinkpress";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::cutPaperByHand(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "manualCutPaper";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::powerOffMachine(){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "poweroff";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

int MsgControl::getCurrentPicIndex(){
    return m_CurrentPicIndex;
}

void MsgControl::addFilesToList(const QString &filePath,const bool& ret){
    if(ret){
        if(m_SelectedFilesList.contains(filePath))
            return;

        m_SelectedFilesList << filePath;
    }else{
        m_SelectedFilesList.removeOne(filePath);
    }

    //获取width | height | xdpi | ydpi 相关信息
    if(m_SelectedFilesList.size() > 0){
        const QString& file = m_SelectedFilesList.last();
        this->getPicinfo(file,m_PicMd5StrMap[file]);
    }else{
        setShowTapPic(false);
    }
}

void MsgControl::touchPrintFiles(const QString &filePath){
    if(filePath.isEmpty()) return;
    this->getPicinfo(filePath,m_PicMd5StrMap[filePath]);
}

void MsgControl::preAddPrintWork(const int& btnStatus){
    if(1 == btnStatus){
        //打印之前清空已经存在的任务
        removeExistedPrintWorks();
    }else{
        startPrint(btnStatus);
    }
}

void MsgControl::getRipSetting(){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "get_rip_settings";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::setRipSetting(const Json::Value &value){
    Json::Value root = value;
    root["command"] = "set_rip_settings";
    root["data"]["ripimagebuffersize"] = SystemConfig::getInstance()->value("rip/ripCacheSize",4*1014*1024).toInt();
    root["data"]["history_prn_cache_size"] = SystemConfig::getInstance()->value("rip/prnCacheSize",0).toInt();
    root["data"]["print_begin_rip_percent"] = 0;

//    //挂网线程数[1,32]
//    if(32 <  getSytemCPU_Counts()){
//        m_RIPThreads = 32;
//    }else{
//        if(m_RIPThreads > getSytemCPU_Counts())
//             m_RIPThreads = getSytemCPU_Counts();
//    }

    root["data"]["halftone_threadnum"] = 32;
    root["data"]["ripserver_opt"] = [&]{
        Json::Value root;
        root["halftone"] = 32;
        root["halftoneBufferMaxSize"] = 268435456;
        root["halftoneBufferMaxLines"] = 256;
        root["interpretation"] = true;
        root["threadBufferMaxSize"] = 4194304;
        root["threadBufferMaxLines"] = 1024;
        root["multiImageBlockMaxSize"] = 67108864;
        root["multiImageBlockMaxLines"] = 1024;
        root["multiImageBlockThreads"] = m_RIPThreads;
        root["halftoneCache"] = true;
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::setPageChange(const int &page){
    emit pageChanged(page);
}

void MsgControl::deleteFileFromDisk(){
    if(m_SelectedFilesList.isEmpty()){
        return;
    }

    //记录当删除文件所在的目录
    QString filePath = m_SelectedFilesList.last();

    //用于删除目录下文件更新
    m_CurFileFolder = filePath.mid(0,filePath.lastIndexOf("/"));

    Json::Value root;
    root["type"] = "system";
    root["command"] = "delete_file";
    root["data"] = [&]{
        Json::Value root;
        root["filepath"] = [&]{
            Json::Value root;
            for(const auto& file:m_SelectedFilesList){
                root.append(file.toStdString());
            }
            return root;
        }();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

///server端返回消息分发处理
///***********************************************************************************/
//缩略图
void MsgControl::doCallBinaryBack(const QByteArray& data){
    uint spi_pos = qstrlen(data.data());
    const QByteArray& json_byte = data.left(spi_pos);

    Json::Reader reader;
    Json::Value root;

    if(!reader.parse(json_byte.toStdString(), root)) {
        return;
    }

    const QString picName = root["dataDetail"]["filename"].asCString();
    const QImage& pic = QImage::fromData(data.right(data.size() - spi_pos - 1));

    emit onAddImage(new SmallPic_Struct(picName,pic));
}

//服务端的响应消息
void MsgControl::doCallBack(const QString& msg){
    if(SystemConfig::getInstance()->value("info/flag",false).toBool()){
        qDebug() << "msg receive : " << msg;
    }

    Json::Reader reader;
    Json::Value root;

    if(!reader.parse(msg.toStdString(), root)) {
        return;
    }

    const QString command = root["command"].asCString();

    if("poweronSelfcheck" == command){
          dealCallSelfCheck(root);
    }else if("print_start" == command){
          dealCallStartPrint(root);
    }else if("print_pause" == command){
          dealCallPausePrint(root);
    }else if("print_resume" == command){
          dealCallResumePrint(root);
    }else if("print_cancel" == command){
          dealCallCancelPrint(root);
    }else if("open_filesystem" == command){
          dealCallRootDirList(root);
    }else if("get_filesystem_info" == command){
          dealCallRootDirList(root);
    }else if("filesystem_dirback" == command){
          dealCallRootDirList(root);
    }else if("ripserver_query_mode" == command){
          dealCallGetRipMode(root);
    }else if("get_ripservermode_alias" == command){
          dealCallGetRipModeNameAlias(root);
    }else if("ripserver_query_picinfo" == command){
          dealCallPicinfo(root);
    }else if("print_list_add" == command){
          dealCallAddPrintList(root);
    }else if("print_list_read" == command){
          //dealCallPrintWorkList(root);
    }else if("print_list_clear" == command){
          dealCallRemoveExistedPrintWorks(root);
    }else if("setCleanMode" == command){
          dealCallClean(root);
    }else if("SystemManualCommandToolButton" == command){
        const std::string& btn = root["data"]["button"].asString();
        if("test" == btn){
            dealCallTest(root);
        }else if("goorg" == btn){
            dealCallGoorg(root);
        }
    }else if("report_print_progress" == command){
            dealCallPrintProgress(root);
    }else if("report_rip_progress" == command){
            dealCallRipProgress(root);
    }else if("report_warn_message" == command){
            dealCallWarnMessage(root);
    }else if("print_set_task_config" == command){
         //dealCallSetTaskConfig(root);
    }else if("delete_file" == command){
         dealCallDeleteFiles(root);
    }else if("print_status" == command){
         dealCallPrintState(root);
    }else if("uplaodServerFileStatesChanged" == command){
         dealCallUploadFiles(root);
    }else if("get_rip_settings" == command){
        dealCallGetRipSetting(root);
    }else if("set_rip_settings" == command){
        dealCallSetRipSetting(root);
    }else if("getBoardVersion" == command){
        dealCallGetBoardVersion(root);
    }else if("import_icc_profile" == command){
        dealCallImportEvcolor(root);
    }else if("export_icc_profile" == command){
        dealCallExportEvcolor(root);
    }else if("getCommonPrintSetting" == command){
        dealCallGetPrintSetting(root);
    }else if("saveCommonPrintSetting" == command){
        dealCallSavePrintSetting(root);
    }else if("nozzleCalibrationParam" == command){
        const std::string& reg = root["data"]["status"].asCString();
        if("get" == reg){
            dealCallGetPenTouJiaoZhun(root);
        }else if ("set" == reg){
            dealCallSetPenTouJiaoZhun(root);
        }else{
            return;
        }
    }else if("nozzleCalibrationTestImage" == command){
        dealCallNozzleCalibrationTest(root);
    }else if("injectink" == command){
        dealCallInjectInk(root);
    }else if("stopinkpress" == command){
        dealCallStopInjectInk(root);
    }else if("get_hotspot_info" == command){
        dealCallGetWifiQrenCode(root);
    }else if("manualCutPaper" == command){
        dealCallCutPaperByHand(root);
    }else if("setTempBoardParam" == command){
        dealCallSaveTempBoardSetting(root);
    }else if("getTempBoardParam" == command){
        dealCallGetTempBoardSetting(root);
    }else if("getPlatformParam" == command){
        dealCallGetTaiBanSetting(root);
    }else if("setPlatformParam" == command){
        dealCallSaveTaiBanSetting(root);
    }else if("platformBtnClicked" == command){
        dealCallExcuteTaiBan(root);
    }else{
        return;
    }
}

void MsgControl::dealCallStartPrint(const Json::Value& value){
    QVariantMap msgMap;
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        setStartBtnStatus(2);
        setPrintBarShow(true);
    }else{
        if("en" == m_Language){
            msgMap["msg"]  = "Print failed！";
        }else{
            msgMap["msg"]  = "打印失败！";
        }
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
    }

    emit showWaitDia(false); //关闭打印等待对话框
}

void MsgControl::dealCallPausePrint(const Json::Value& value){
    QVariantMap msgMap;
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        this->setStartBtnStatus(3);
        if("en" == m_Language){
            msgMap["msg"]   = "Pause Successully！";
        }else{
            msgMap["msg"]  = "已暂停！";
        }
        msgMap["type"]  = "tip";
    }else{
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallResumePrint(const Json::Value& value){
    QVariantMap msgMap;
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        this->setStartBtnStatus(2);
        if("en" == m_Language){
            msgMap["msg"]   = "Resume Successully！";
        }else{
            msgMap["msg"]  = "已继续打印！";
        }
        msgMap["type"]  = "tip";
    }else{
        msgMap["type"]  = "error";
        if("en" == m_Language){
            msgMap["msg"]   = "Resume Failed！";
        }else{
            msgMap["msg"]  = "继续打印失败！";
        }
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallCancelPrint(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["type"] = "cancel";
    msgMap["msg"]  = "Canceling...";
    msgMap["isShow"]  = false; //为兼容pc上传打印
    msgMap["operatIndex"]  = 0;
    this->setStateTypeMap(msgMap);

    //任务取消后,如果是自动排版状态，则进行一次自动排版 | 不重新排版会不能打印
    if(isAutoBingPack){
        emit onGetBigPic(m_seletePaiBanFileList);
    }else {
        return;
    }
}

void MsgControl::dealCallClean(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["type"] = "normal-clean";
    msgMap["msg"]  = "Cleaning...";
    msgMap["operatIndex"]  = 1;

    const bool& ret =  value["data"]["ret"].asBool();
    if(ret){
        msgMap["isShow"]  = true;
    }else{
        if(QString("wait") == value["data"]["status"].asCString()){
            msgMap["isShow"]  = false;
        }else if(QString("finished") == value["data"]["status"].asCString()){
            msgMap["isShow"]  = true;
        }else{
            msgMap["isShow"]  = true;
        }
    }
    this->setStateTypeMap(msgMap);
}

void MsgControl::dealCallTest(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["type"] = "print";
    msgMap["msg"]  = "Printing...";
    msgMap["operatIndex"]  = 2;
    const bool& ret =  value["data"]["ret"].asBool();
    if(ret){
        msgMap["isShow"]  = true;
    }else{
        if(QString("wait") == value["data"]["status"].asCString()){
            msgMap["isShow"]  = false;
        }else if(QString("finished") == value["data"]["status"].asCString()){
            msgMap["isShow"]  = true;
        }else{
            msgMap["isShow"]  = true;
        }
    }
    this->setStateTypeMap(msgMap);
}

void MsgControl::dealCallGoorg(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["type"] = "restore";
    msgMap["msg"]  = "Restoring...";
    const bool& ret =  value["data"]["ret"].asBool();
    if(ret){
        msgMap["isShow"]  = true;
    }else{
        if(QString("wait") == value["data"]["status"].asCString()){
            msgMap["isShow"]  = false;
        }else if(QString("finished") == value["data"]["status"].asCString()){
            msgMap["isShow"]  = true;
        }else{
            msgMap["isShow"]  = true;
        }
    }
    msgMap["operatIndex"]  = 3;
    this->setStateTypeMap(msgMap);
}

void MsgControl::dealCallRootDirList(const Json::Value& value){
    //清空文件列表
    m_FileList.clear();
    m_SmallPicFilesList.clear();
    m_fileSize.clear();
    m_SeletcedFileMap.clear();

    const Json::Value& data = value["data"]["data"];
    const QString cur_path =  value["data"]["currentdirpath"].asCString();
    QVariantList first_list;
    for(int i = 0 ; i < (int)data.size() ; i++){
        QVariantMap tempMap = {};
        const QString suffix = data[i]["info"]["suffix"].asCString();
        const QString fileType = data[i]["info"]["type"].asCString();
        if("file" == fileType && !fileSupportList.contains(suffix)){
              continue;
        }

        tempMap["type"] = fileType;
        tempMap["suffix"] = suffix;
        tempMap["name"] = data[i]["name"].asCString();
        tempMap["md5id"] = data[i]["info"]["md5id"].asCString();
        tempMap["uuid"] = data[i]["info"]["uuid"].asCString(); //此时uuid为空
        tempMap["abs_path"] = data[i]["info"]["abs_path"].asCString();
        tempMap["cur_dirpath"] = cur_path;
        first_list << tempMap;

        if(fileSupportList.contains(suffix)){
            QVariantMap tempMap1 = {};
            tempMap1["name"] = data[i]["name"].asCString();
            tempMap1["md5id"] = data[i]["info"]["md5id"].asCString();
            m_SmallPicFilesList << tempMap1;
            float fileSize = data[i]["info"]["filesize"].asFloat()/1024/1024;
            m_fileSize[tempMap["abs_path"].toString()] = QString::number(fileSize, 'f', 3);//文件大小
        }
    }

    emit onCurrentFolderPicInfo(cur_path);

    //获取到当前目录下的文件夹、及文件名称
    this->setFileList(first_list);
    //开始请求获取文件的缩略图
    this->getSmallPic();
}

void MsgControl::getSmallPic(){
    if(m_SmallPicFilesList.size() <= 0) return;
    for(const auto& map : m_SmallPicFilesList){
        Json::Value root;
        root["type"] = "system";
        root["command"] = "filesystem_geticon";
        root["data"] =[&](){
            Json::Value root;
            root["filename"] = QString(map.toMap()["name"].toString()).toStdString();
            root["md5id"] = QString(map.toMap()["md5id"].toString()).toStdString();
            return root;
        }();

        Json::FastWriter writer;
        const std::string json_file = writer.write(root);
        m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
    }
}

void MsgControl::dealCallGetRipMode(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(!msgMap["flag"].toBool()){
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
    }else{
        const Json::Value& data = value["data"]["modes"];
        //将相同的paper属性曲线整合到一起
        QVariantMap tempEcolorMap = {};
        for(int i = 0 ; i < (int)data.size() ; i++){
            QString name = data[i]["name"].asCString();
            QString dpi = data[i]["dpi"].asCString();
            QString ink = data[i]["ink"].asCString();
            QString paper = data[i]["paper"].asCString();

            QString aliasName;
            try {
                aliasName = m_RipAliasMap["data"]["data"][name.toStdString()].asCString();
            } catch (std::exception e){
                aliasName = dpi+" "+ink;
            }

            QVariantList list;
            list << aliasName;
            if(tempEcolorMap.contains(paper)){
                QVariantList* p_list = (QVariantList*)tempEcolorMap[paper].data();
                *p_list << list;
            }else{
                tempEcolorMap[paper] = list;
            }

            QString finalEcolorKey = paper+" "+dpi+" "+ink;
            m_FinalEcolorLine[finalEcolorKey] = name;
        }

        //将相同的paper属性曲线map,转换成list,便于qml代理元素进行遍历
        QVariantList printPaperList = {};
        QVariantMap  printEcolorMap = {};
        for (QVariantMap::const_iterator iter = tempEcolorMap.constBegin(); iter != tempEcolorMap.constEnd(); ++iter) {
            QString key = iter.key();
            printPaperList << key;

            QVariantList value = iter.value().toList();
            printEcolorMap[key] = value;
        }

        setPrintPaperStyle(printPaperList);
        setQualityMode(printEcolorMap);
    }
}

void MsgControl::dealCallGetRipModeNameAlias(const Json::Value &root){
    m_RipAliasMap = root;
}

void MsgControl::dealCallPicinfo(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["msg"]   = value["data"]["message"].asCString();
    bool ret = value["data"]["ret"].asBool();
    msgMap["flag"]  = false;

    if(!ret){
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
    }else{
        QString filePath = value["data"]["picinfo"]["filepath"].asCString();
        QVariantMap tempMap;
        const QString fileName = filePath.split("/").last();
        tempMap.clear();
        float w = value["data"]["picinfo"]["width"].asFloat();
        float h = value["data"]["picinfo"]["height"].asFloat();
        tempMap["height"] = h; //QString::number(h, 'f', 3).toFloat();
        tempMap["width"] = w;  //QString::number(w, 'f', 3).toFloat();
        tempMap["xdpi"] = value["data"]["picinfo"]["xdpi"].asInt();
        tempMap["ydpi"] = value["data"]["picinfo"]["ydpi"].asInt();
        tempMap["uuid"] = value["data"]["picinfo"]["uuid"].asCString();
        tempMap["name"] = fileName;
        tempMap["size"] = m_fileSize[filePath];

        QVariantMap tempMap1;
        if("mm" == m_SizeUnit){
            tempMap1["height"] = QString::number(h);
            tempMap1["width"] = QString::number(w);
            tempMap1["uuid"] =  value["data"]["picinfo"]["uuid"].asCString();
            tempMap1["name"] = fileName;
            tempMap1["size"] = m_fileSize[filePath];
            setPicPropertyMap(tempMap1);
        }else{
            tempMap1["height"] = QString::number(h*10/254, 'f', 3);
            tempMap1["width"] = QString::number(w*10/254, 'f', 3);
            tempMap1["uuid"] =  value["data"]["picinfo"]["uuid"].asCString();
            tempMap1["name"] = fileName;
            tempMap1["size"] = m_fileSize[filePath];
            setPicPropertyMap(tempMap1);//更新页面当前的图片信息
        }

        m_FileInfoMap[filePath] = tempMap;
    }
}

void MsgControl::dealCallAddPrintList(const Json::Value &value){
    startPrint(1);
}

void MsgControl::dealCallRemoveExistedPrintWorks(const Json::Value & value){
    bool ret = value["data"]["ret"].asBool();
    QVariantMap msgMap;
    msgMap["flag"]  = ret;

    if(ret){
        addPrintWork();
    }else{
        if("en" == m_Language){
             msgMap["msg"]   = value["data"]["message"].asCString();
        }else{
            msgMap["msg"] = value["data"]["message"].asCString();;
        }
        msgMap["type"]  = "error";

        this->setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallRipProgress(const Json::Value & value){
    const QString& state  = value["data"]["state"].asCString();
    if("wrong" == state){
        setPrintBarShow(false);

        QVariantMap msgMap;
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        msgMap["msg"] = value["data"]["message"].asCString();
        this->setErrorMsg(msgMap);
    }else{
        int ripProgress = value["data"]["progress"].asInt();
        QString msg = "";
        if(100 > ripProgress){
            if("cn" == m_Language){
                msg = "RIP中...";
            }else{
                msg = "RIPPing...";
            }
        }else{
            if("cn" == m_Language){
                msg = "";
            }else{
                msg = "";
            }
        }
        ripPrintInfo(0,ripProgress,msg);
    }
}

void MsgControl::dealCallPrintProgress(const Json::Value & value){
    const QString& state  = value["data"]["state"].asCString();
    if("wrong" == state){
        setPrintBarShow(false);
    }else{
        int printProcess = value["data"]["progress"].asInt();
        QString msg = "";
        if(printProcess < 100){
            if("cn" == m_Language)
                msg = "打印中...";
            else
                msg = "Printing...";
        }else{
            if("cn" == m_Language)
                msg = "";
           else
                msg = "";

            initPrintState();
        }
        ripPrintInfo(1,printProcess,msg);
    }
}

void MsgControl::dealCallWarnMessage(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["flag"] = false;
    msgMap["type"]  = "error";

    uint code = 0;
    QString tempType = value["data"]["type"].asCString();
    if("warn" == tempType || "fatal" == tempType){
        QString analyse = "analyse:";
        QString solution = "solution:";
        QString errorCode = "errorCode:";
        QString msg = value["data"]["message"].asCString();
        msg.append("\n");
        if("cn" == m_Language){
            errorCode = "错误码:";
            analyse = "可能原因:";
            solution = "解决方案:";
        }

        //错误码
        msg.append(errorCode);
        code = value["data"]["errorcode"].asUInt();
        msg.append(QString::number(code));
        msg.append("\n");

        //原因分析
        if(!QString(value["data"]["analysismessage"].asCString()).isEmpty()){
            msg.append(analyse);
            msg.append(value["data"]["analysismessage"].asCString());
            msg.append("\n");
        }

        //解决方法
        if(!QString(value["data"]["solutionmessage"].asCString()).isEmpty()){
            msg.append(solution);
            msg.append(value["data"]["solutionmessage"].asCString());
        }

        msgMap["msg"] = msg.trimmed();

        if(1064 == code){
            emit antiCollisionState(msgMap);
            setStartBtnStatus(3);//暂停
            return;
        }

        this->setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallDeleteFiles(const Json::Value &value){
    QVariantMap msgMap;
    const bool& ret  = value["data"]["ret"].asBool();
    if(ret){
        msgMap["flag"] = true;
        msgMap["type"]  = "tip";
        if("en" == m_Language){
             msgMap["msg"] = "Delete files Successfully !";
        }else{
             msgMap["msg"] = "已删除文件!";
        }
        getNext_DirInfo(m_CurFileFolder);
    }else{
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        if("en" == m_Language){
             msgMap["msg"]   = "Delete files failed !";
        }else{
             msgMap["msg"] = "删除文件失败!";
        }
    }

    m_SelectedFilesList.clear();
    setSelectPicture(false);
    setErrorMsg(msgMap);
}

void MsgControl::dealCallPrintState(const Json::Value &value){
    const QString state = value["data"]["info"]["status"].asCString();

    if("print" == state){
        m_IsCanceled = false;
    }else if("idle" == state){
        m_IsCanceled = true;

        QVariantMap msgMap;
        msgMap["type"] = "cancel";
        msgMap["msg"]  = "Canceling...";
        msgMap["isShow"]  = true;
        this->setStateTypeMap(msgMap);

        //出错重置
        [&]{
            m_SelectedFilesList.clear();
            m_FileInfoMap.clear();
            setPrintBarShow(false);
            setStartBtnStatus(1); //重置按钮状态
        }();
    }
}

void MsgControl::dealCallUploadFiles(const Json::Value &value){
    bool ret = value["data"]["ret"].asBool();
    if(ret){
        getWifi_FileDir();
        emit changeGetFileBtn(1);
    }
}

void MsgControl::dealCallGetRipSetting(const Json::Value &value){
    const bool ret = value["data"]["ret"].asBool();
    if(ret){
        setRipSetting(value);
    }else{
        QVariantMap msgMap;
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        msgMap["msg"]   = "Get RIP Properties Failed!";
        this->setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallSetRipSetting(const Json::Value &value){
    const bool ret = value["data"]["ret"].asBool();
    if(!ret){
        QVariantMap msgMap;
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        msgMap["msg"]   = "Set RIP Properties Failed!";
        this->setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallGetBoardVersion(const Json::Value &value){
    QVariantMap map = {{"State",false},\
                       {"Message","BoardVersion is null"},\
                       {"RIP-Server","NUll"},\
                       {"InterfaceBoard","Null"},\
                       {"NozzleBoard","Null"},\
                       {"MotorBoard","Null"},\
                       {"PrintEngine","Null"}
                      };
    if(value["data"]["ret"].asBool()){
        map["State"] = true;
        map["Message"] = "";
        map["PrintDriver"] = value["data"]["SoftVersion"].asCString();
        QString str = value["data"]["printEngineVersion"].asCString();
        const QStringList strList = str.split("-");
        map["RipServer"] = strList.at(0);
        const QString str1 = strList.at(1);
        map["PrintEngine"] = str1.split("[").at(0);
        map["InterfaceBoard"] = value["data"]["InterfaceBoardVersion"].asCString();
        map["NozzleBoard"] = value["data"]["NozzleBoardVersion"].asCString();
        map["MotorBoard"] = value["data"]["MotorBoardVersion"].asCString();
    }
    setBoardVersion(map);
}

void MsgControl::dealCallImportEvcolor(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["flag"] = false;
    if(value["data"]["ret"].asBool()){
       msgMap["type"]  = "tip";
       if("en" == m_Language){
            msgMap["msg"]   = "Import Evcolor Successfully!";
       }else{
           msgMap["msg"] = "曲线导入成功!";
       }

       //曲线导入成功后，更新打印曲线参数
       getRipModeNameAlias();
       getRipMode();
    }else{
       msgMap["type"]  = "error";
       msgMap["msg"]   = value["data"]["message"].asCString();
    }
    setErrorMsg(msgMap);
}

void MsgControl::dealCallExportEvcolor(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["flag"] = false;
    if(value["data"]["ret"].asBool()){
       msgMap["type"]  = "tip";
       if("en" == m_Language){
            msgMap["msg"]   = "Export Evcolor Successfully!";
       }else{
           msgMap["msg"] = "曲线导出成功!";
       }
    }else{
       msgMap["type"]  = "error";
       msgMap["msg"]   = value["data"]["message"].asCString();
    }
    setErrorMsg(msgMap);
}

void MsgControl::dealCallSelfCheck(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["flag"] = false;
    const bool& ret = value["data"]["ret"].asBool();
    if(ret){
       msgMap["type"] = "tip";
       if("en" == m_Language){
            msgMap["msg"] = "SelfCheck Successfully!";
       }else{
            msgMap["msg"] = "自检完成!";
       }
    }else{
       msgMap["type"] = "error";
       if("en" == m_Language){
           msgMap["msg"] = "SelfCheck Failed!";
       }else{
           msgMap["msg"] = "自检失败!";
       }
    }

    emit selfCheckResult(ret);
    setErrorMsg(msgMap);

    //自检完成之后，再进行查询queryMode和queryAlias操作
    getRipModeNameAlias();
    getRipMode();
}

void MsgControl::dealCallGetWifiQrenCode(const Json::Value &root){
    if(root["data"]["ret"].asBool()){
        QString wifiName = root["data"]["wifiHotspotInfo"]["wifiName"].asCString();
        QString passWord = root["data"]["wifiHotspotInfo"]["password"].asCString();

        QString wifiNameStr = QString("WIFI:S:%1;T:WPA2;P:%2;").arg(wifiName).arg(passWord);
        QString httphead = "http://";
        QString hostIp   = httphead.append(root["data"]["wifiHotspotInfo"]["hotspotIp"].asCString());

        generateWifiCode(wifiNameStr,"/mnt/nvme/qmlPrint/wifi_key.png");
        generateWifiCode(hostIp,"/mnt/nvme/qmlPrint/web_http.png");

        emit refreshCodeImage(wifiName,passWord);
    }
}

void MsgControl::dealCallGetPrintSetting(const Json::Value &value){
    QVariantMap msgMap;
    if(!value["data"]["ret"].asBool()){
       msgMap["flag"] = false;
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = "GetPrintSetting Error!";
       }else{
           msgMap["msg"] = "打印配置信息获取错误!";
       }
       setErrorMsg(msgMap);
       return;
    }

    const std::string objStr = cppJson_To_String(value["data"]["struct"]);
    xpack::json::decode(objStr,m_PrintSetting);

    QVariantMap map;
    map["startPos"] = m_PrintSetting.PrintStartPositionMM;
    map["paperWidth"] = m_PrintSetting.PaperWidth;
    map["printSpeed"] = m_PrintSetting.PrintSpeedSelect;
    map["printDirection"] = m_PrintSetting.PrintDirectionSelect;

    map["enableYuHua"] = m_PrintSetting.PrintFeatherEnable;
    map["startShanPen"] = m_PrintSetting.bFlashBeforePrint;
    map["yuHuaMode"] = m_PrintSetting.PrintFeatherSelect;
    map["yuHuaPercent"] = [&]{
        QVariantList list;
        list << m_PrintSetting.PrintFeatherPercent[0] << m_PrintSetting.PrintFeatherPercent[1];
        return list;
    }();
    map["openCaiTiao"] = m_PrintSetting.bColorBarEnable;
    map["caiTiaoSelect"] = m_PrintSetting.ColorBarSelect;
    map["caiTiaoWidth"] = m_PrintSetting.ColorBarWidth;
    map["caiTianGap"] = m_PrintSetting.ColorBarGap;
    map["caiTiaoNongDu"] = m_PrintSetting.ColorBarConcPercentage;
    map["bUseCutter"] = m_PrintSetting.bUseCutter;

    emit sendPrintSetting(map);

    //打印之前检查纸张是否超出驱动设定范围之
    if(isCheckMachineOutWidth){
        if(m_PaperWidth.toDouble() > m_PrintSetting.PaperWidth){
            if("en" == m_Language){
                msgMap["msg"]   = "OverSize,Adjust the output width parameter to accommodate the overflow, or modify the page width for printing!";
            }else{
                msgMap["msg"]   = "超出打印宽幅，请先调整输出宽幅参数，或者修改排版纸张宽幅!";
            }
            msgMap["type"]  = "error";
            this->setErrorMsg(msgMap);
            isCheckMachineOutWidth = false;
            return;
        }
        isCheckMachineOutWidth = false;

        emit showWaitDia(true);
        //固定排版所需
        if(!isAutoBingPack){
            //emit onGetBigPic(m_seletePaiBanFileList);
            QVariantList list = {};
            emit onGetBigPic(list);
        }else{
            preAddPrintWork(1);
        }
    }
}

void MsgControl::dealCallSavePrintSetting(const Json::Value &value){
    QVariantMap msgMap;
    if(!value["data"]["ret"].asBool()){
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = value["data"]["message"].asCString();
       }else{
           msgMap["msg"] = "参数保存失败!";
       }
       setErrorMsg(msgMap);
       return;
    }else{
        msgMap["type"]  = "tip";
        if("en" == m_Language){
             msgMap["msg"]  = "Save Successfully!";
        }else{
            msgMap["msg"] = "参数保存成功!";
        }
        setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallGetPenTouJiaoZhun(const Json::Value &value){
    if(!value["data"]["ret"].asBool()){
       QVariantMap msgMap;
       msgMap["flag"] = false;
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = "Get NozzleCalibrationParam Error!";
       }else{
           msgMap["msg"] = "喷头校准参数获取错误!";
       }
       setErrorMsg(msgMap);
       return;
    }

    const std::string objStr = cppJson_To_String(value["data"]["struct"]);
    xpack::json::decode(objStr,m_NozzlCalibrate);

    QVariantMap map;
    map["printMeterialName"] = [&]{
        QVariantList list;
        foreach(const QString& str,m_NozzlCalibrate.printMaterialNames){
            list << str;
        }
        return list;
    }();
    map["printMeterial"]        =  m_NozzlCalibrate.calibrationMaterial;
    map["printSpeed"]           =  m_NozzlCalibrate.calibrationSpeed;
    map["printJingDu"]          =  m_NozzlCalibrate.calibrationXDpi;
    map["printTestPaperWidth"]  =  m_NozzlCalibrate.calibrationPrintWidth;

    //喷头废孔  i (0-前废孔，1-后废孔)
    QVariantList vertialColorlist;
    vertialColorlist.clear();
    for(int i = 0; i < BOOLEAN_MAX_NUMBER; i++)
    {
        for(int iGroup = 0; iGroup < (int)m_NozzlCalibrate.machineGroupNumber; iGroup++)
        {
            for(int iColor = 0; iColor < (int)m_NozzlCalibrate.machineColorNumber; iColor += m_NozzlCalibrate.oneNozzleColorNumber)
            {
                vertialColorlist << m_NozzlCalibrate.invalidNozzleNumber[iColor][iGroup][i];
                //i = 0,1  彩 白 前废孔
                //i = 2,3  彩 白 后废孔
            }
        }
    }
    map["printVerticalCheck"] = vertialColorlist;

    //横向组间距
    /*QVariantList horientColorlist;
    horientColorlist.clear();
    for(int i = 0; i < BOOLEAN_MAX_NUMBER; i++)
    {
         for(uint32_t iGroup = 0; iGroup < m_NozzlCalibrate.machineGroupNumber; iGroup++)
         {
             for(int iColorGroup = 0; iColorGroup < m_NozzlCalibrate.oneGroupNozzleNumber; iColorGroup++)
             {
                 horientColorlist << m_NozzlCalibrate.horzGroupSpacing[i][m_NozzlCalibrate.calibrationXDpi][m_NozzlCalibrate.calibrationSpeed][iGroup][iColorGroup];
                 //i = 0,2 左 彩白
                 //i = 1,3 右 彩白
             }
         }
     }
     map["horientColorlist"] = horientColorlist;*/

     //基准套色
     QVariantList mutilColorslist;
     mutilColorslist.clear();
     for (int i = 0; i < BOOLEAN_MAX_NUMBER; i++)
     {   QVariantList colorslist;
         for(uint32_t iGroup = 0; iGroup < m_NozzlCalibrate.machineGroupNumber; iGroup++)
         {
             for(uint32_t iColor = 0; iColor < m_NozzlCalibrate.machineColorNumber; iColor++)
             {
                 colorslist << m_NozzlCalibrate.baseNozzleOffset[i][m_NozzlCalibrate.calibrationXDpi][iColor][iGroup];
             }
         }
         mutilColorslist << QVariant::fromValue(colorslist);
     }
     map["mutilColorslist"] = mutilColorslist;

     //组内套色
     QVariantList zuNeiColorslist;
     zuNeiColorslist.clear();
     zuNeiColorslist << m_NozzlCalibrate.horzGroupsOffset[m_NozzlCalibrate.calibrationXDpi][m_NozzlCalibrate.oneNozzleColorNumber];
     zuNeiColorslist << m_NozzlCalibrate.stepAdjustOffset[m_NozzlCalibrate.oneNozzleColorNumber];
     map["zuNeiColorslist"] = zuNeiColorslist;

    //双向套色
    QVariantList shuanXiangColorlist;
    shuanXiangColorlist.clear();
    for(int iGroupColor = 0; iGroupColor < (int)m_NozzlCalibrate.machineColorNumber; iGroupColor+= m_NozzlCalibrate.oneNozzleColorNumber)
    {
        //iGroupColor = 0 彩 iGroupColor = 1 白
        shuanXiangColorlist << m_NozzlCalibrate.doubleNozzleOffset[m_NozzlCalibrate.calibrationMaterial][m_NozzlCalibrate.calibrationXDpi][m_NozzlCalibrate.calibrationSpeed][iGroupColor][0];
    }
    map["shuangxiangCheck"] = shuanXiangColorlist;

    emit sendPrintJiaoZhun(map);
}

void MsgControl::dealCallSetPenTouJiaoZhun(const Json::Value &value){
    QVariantMap msgMap;
    if(!value["data"]["ret"].asBool()){
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = value["data"]["message"].asCString();
       }else{
           msgMap["msg"] = "参数保存失败!";
       }
       setErrorMsg(msgMap);
       return;
    }else{
        msgMap["type"]  = "tip";
        if("en" == m_Language){
             msgMap["msg"]  = "Save Successfully!";
        }else{
            msgMap["msg"] = "参数保存成功!";
        }
        setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallSaveTempBoardSetting(const Json::Value & value){
    QVariantMap msgMap;
    if(!value["data"]["ret"].asBool()){
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = value["data"]["message"].asCString();
       }else{
           msgMap["msg"] = value["data"]["message"].asCString();
       }
       setErrorMsg(msgMap);
       return;
    }else{
        msgMap["type"]  = "tip";
        if("en" == m_Language){
             msgMap["msg"]  = "Save Successfully!";
        }else{
            msgMap["msg"] = "参数保存成功!";
        }
        setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallGetTempBoardSetting(const Json::Value &value){
    if(!value["data"]["ret"].asBool()){
       QVariantMap msgMap;
       msgMap["flag"] = false;
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = "Get TempBoard Params Failed!";
       }else{
           msgMap["msg"] = "温控板参数获取错误!";
       }
       setErrorMsg(msgMap);
       return;
    }

    const std::string objStr = cppJson_To_String(value["data"]["parms"]);
    xpack::json::decode(objStr,m_TempBoardAllPARAM);

    QVariantMap map;
    map["frontHeatTemp"]     = m_TempBoardAllPARAM.frontHeatTemp;
    map["realFrontHeatTemp"] = m_TempBoardAllPARAM.realFrontHeatTemp;
    map["middleHeatTemp"]    = m_TempBoardAllPARAM.middleHeatTemp;
    map["realMiddleHeatTemp"] = m_TempBoardAllPARAM.realMiddleHeatTemp;
    map["rearHeatTemp"]      = m_TempBoardAllPARAM.rearHeatTemp;
    map["realRearHeatTemp"]  = m_TempBoardAllPARAM.realRearHeatTemp;
    map["fanGear"]           = m_TempBoardAllPARAM.fanGear;
    map["realFanGear"]       = m_TempBoardAllPARAM.realFanGear;
    map["lightState"]        = m_TempBoardAllPARAM.lightState;
    map["realLightState"]    = m_TempBoardAllPARAM.realLightState;

    emit sendTempBoardPara(map);
}

void MsgControl::dealCallNozzleCalibrationTest(const Json::Value &value){
    const bool& ret = value["data"]["ret"].asBool();
    if("GearRatioCalibration" == value["data"]["button"].asString()){
        QVariantMap msgMap;
        msgMap["type"]  = "tip";
        if("en" == m_Language){
             msgMap["msg"]  = "Caculate MotorRate Successfully!";
        }else{
            msgMap["msg"] = "齿轮比计算成功!";
            emit clearVertMotorRate();
        }
        setErrorMsg(msgMap);
        return;
    }

    QVariantMap msgMap;
    msgMap["type"] = "print";
    msgMap["msg"]  = "Printing...";
    msgMap["isShow"]  = ret;
    msgMap["operatIndex"]  = 2;
    this->setStateTypeMap(msgMap);
}

void MsgControl::dealCallInjectInk(const Json::Value &root){
      static int cal = 0;
      bool b = root["data"]["ret"].asBool();
      QString msg = "";
      if(b){
          msg = "注墨成功！";
          cal = 0;
          emit inkInjectState(b,msg);
      }else{
          cal++;
          msg = root["data"]["message"].asCString();
          if(1 < cal){
              b = true;
              cal = 0;
          }else{
              b = false;
          }
          emit inkInjectState(b,msg);
      }
}

void MsgControl::dealCallStopInjectInk(const Json::Value &root){
    const bool b = root["data"]["ret"].asBool();
    QString msg = "";
    if(b){
        msg = "已停止注墨！";
    }else{
        msg = root["data"]["message"].asCString();
    }
    emit stopInkInjectState(b,msg);
}

void MsgControl::dealCallCutPaperByHand(const Json::Value& root){
    const bool b = root["data"]["ret"].asBool();
    QString msg = "";
    QVariantMap msgMap;
    msgMap["flag"] = false;

    QString tempType = QString::fromStdString(root["data"]["status"].asString()); // wait | finished

    if(!b){
        if("wait" == tempType ){
            if("en" == m_Language){
                msg = "cutting...";
            }else{
                msg = "切纸中...";
            }
        }else if("finished" == tempType){
            msgMap["type"] = "tip";
            msgMap["msg"] = root["data"]["message"].asCString();
            setErrorMsg(msgMap);
        }
    }else{
        msgMap["type"] = "tip";
        if("en" == m_Language){
             msgMap["msg"] = "CutPaper Successfully!";
        }else{
             msgMap["msg"] = "切纸完成!";
        }
        setErrorMsg(msgMap);
    }

    emit cutPaper(b,tempType);
}

void MsgControl::dealCallGetTaiBanSetting(const Json::Value& root){
    if(!root["data"]["ret"].asBool()){
       QVariantMap msgMap;
       msgMap["flag"] = false;
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = QString::fromStdString(root["data"]["message"].asString());
       }else{
           msgMap["msg"] = "台板参数获取错误!";
       }
       setErrorMsg(msgMap);
       return;
    }

    const std::string objStr = cppJson_To_String(root["data"]["parms"]);
    xpack::json::decode(objStr,m_PlatformsPARAM);

    m_PlatformNameList.clear();
    m_PlatformsList.clear();

    for(int i = 0; i < m_PlatformsPARAM.platformNum; i++){
        QVariantMap innerMap;
        if(0 == strlen(m_PlatformsPARAM.platformsSetParam[i].platName)){
            innerMap["platName"] = "null";
            m_PlatformNameList << "null";
        }else{
            innerMap["platName"] = QString::fromUtf8(m_PlatformsPARAM.platformsSetParam[i].platName);
            m_PlatformNameList << m_PlatformsPARAM.platformsSetParam[i].platName;
        }
        innerMap["width"] = m_PlatformsPARAM.platformsSetParam[i].width;
        innerMap["height"] = m_PlatformsPARAM.platformsSetParam[i].height;
        innerMap["xPos"] = m_PlatformsPARAM.platformsSetParam[i].xPos;
        innerMap["yPos"] = m_PlatformsPARAM.platformsSetParam[i].yPos;

        m_PlatformsList << innerMap;
    }

    emit taiBanList(m_PlatformNameList,m_PlatformsList,m_PlatformsPARAM.platformOrgToPrintDistance);
}

void MsgControl::dealCallSaveTaiBanSetting(const Json::Value& root){
    QVariantMap msgMap;
    if(!root["data"]["ret"].asBool()){
       msgMap["type"]  = "error";
       if("en" == m_Language){
            msgMap["msg"]  = root["data"]["message"].asCString();
       }else{
           msgMap["msg"] = root["data"]["message"].asCString();
       }
    }else{
        msgMap["type"]  = "tip";
        if("en" == m_Language){
             msgMap["msg"]  = "Save Successfully!";
        }else{
            msgMap["msg"] = "参数保存成功!";
        }
    }
    setErrorMsg(msgMap);
}

void MsgControl::dealCallExcuteTaiBan(const Json::Value& root){
    QVariantMap msgMap;
    bool ret = root["data"]["ret"].asBool();
    emit taiBanState(ret);
}
